2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

VB.netのハテナ 1回の接続で連続してselect文を発行する方法

Last updated at Posted at 2017-09-29

毎回接続しても、コストは微々たるものなので、どちらでもいいのかなと思うのですが、
こんな書き方もできるようです。

開発環境:Visual Studio 2015、VB、フォームアプリ

連続でselect文発行
    
    Imports System.Data.SqlClient 

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Using cn As SqlConnection = New SqlConnection()

            cn.ConnectionString = "接続文字列…"
            cn.Open()

            Dim command As New SqlClient.SqlCommand

            'コマンドの種類をテキストにする(省略可)
            command.CommandType = CommandType.Text
            '実行するSQLを指定
            'ここで複数のSelect文を設定し、sr.NextResult() で次の結果に移る。
            command.CommandText = "SELECT … FROM マスタAAA; " +        '←1つ目【最後にセミコロン要】
                                  "SELECT … FROM マスタBBB "          '←2つ目

            'コネクションの指定
            command.Connection = cn

            'SQLの結果を取得する
            Dim sr As SqlDataReader = command.ExecuteReader()


            '【1つ目】----------
            If sr.HasRows Then
                '有り
                While sr.Read()
                    '処理
                End While
            Else
                'データ無し
            End If

            sr.NextResult()             '<==========次の結果に移る!!!。


            '【2つ目】----------
            If sr.HasRows Then
                '有り
                While sr.Read()
                    '処理
                End While
            Else
                'データ無し
            End If

        End Using
    End Sub
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?