VB.Netのお勉強



ADO.NetでSQLServerに接続@VB.Net

ADO.NetでSQLServerに接続します。

接続文字列を作成し、SqlConnecを生成します。
Openで接続を行います。

SQL文を作成し、SqlCommandを生成します。
ExecuteReaderにより、結果をSqlDataReaderにて取得します。

Readにより、結果を取得し、
Whileでループ処理を行い結果を表示します。


Imports System.Data.SqlClient

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim connectionStr As String
    Dim sqlStr As String

    Try
        '接続
        connectionStr = "Server=localhost\SQLEXPRESS;Initial Catalog=DBName;User ID=sa;Password=pass"

        'SQL文
        sqlStr = "Select * From TableName"

        'コネクション生成
        Using con = New SqlConnection(connectionStr)

            '接続
            con.Open()

            'SqlCommand生成
            Dim cmd = New SqlCommand(sqlStr, con)

            'SELECT文発行
            Dim reader = cmd.ExecuteReader()

            '結果を表示
            While reader.Read()
                Console.WriteLine(reader("ID").ToString() + ":" + reader("NAME"))
            End While
        End Using

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
End Class




Copyright (C) 2008-2011 VB.Netのお勉強. All Rights Reserved.