■  接続型READ

データリーダーを使用してデータベースに高速にアクセスする例です。
この例ではMicrosoftSQLServerのデータベースです。

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
                                                                    Handles Button1.Click
        Dim cn As New SqlClient.SqlConnection  'SQL接続用オブジェクト
        Dim cmd As New SqlClient.SqlCommand    'SQL接続コマンド
        Dim dr As SqlClient.SqlDataReader      'データリーダー
        Dim ttt As String

        '接続文字列を指定
        cn.ConnectionString = "Integrated Security=SSPI;" & _
                   "Persist Security Info=False;" & _
                   "Initial Catalog=TESTDB;" & _
                   "Data Source=FUKU;" & _
                   "Workstation ID=FUKU;"

        '接続
        Try
            cn.Open()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try


        'コマンド作成
        cmd.Connection = cn

        'クエリ文字列を指定する
        cmd.CommandText = "SELECT * FROM TEST_tbl WHERE NAME = 'BBB'"

        'クエリを実行して DataReader を確立する
        Try
            dr = cmd.ExecuteReader
        Catch ex As Exception
            MessageBox.Show(ex.Message & ControlChars.CrLf & cmd.CommandText)
        End Try

        'DataReaderから1行ずつ読み込む
        Do While (dr.Read())
            'リストボックスに フィールドの内容を追加する
            ttt = dr.Item("ID")
            ttt &= Space(1) & dr.Item("NAME")
            ListBox1.Items.Add(ttt)
        Loop
        dr.Close()
        cn.Close()

    End Sub

※接続文字列は、それぞれの環境(認証タイプ等)により異なります。サーバーエクスプローラーで接続しデータリンクプロパティの「その他」タブを参考にしてください。

※データリーダーを使用した後は、必ずCLOSEします。


BEFORE PAGE

TOP PAGE