「VB.NET」SQLServerに接続してSELECT構文を実行するサンプル

書式
1.SqlClientをインポートします
Imports System.Data.SqlClient
Conn.ConnectionString = xxx

2.usingステートメントを利用します
Using Conn As New SqlConnection

3.DBサーバーに接続する文字列の定義
コンピューター名とインスタンス名を指定します
Data Source=localhost\SQLEXPRESS;

データベース名を指定します
Initial Catalog=sampleDB;

4.SQL文を実行します
Using reader As SqlDataReader = cmd.ExecuteReader()

使用例

Imports System.Data.SqlClient

Module Module1
      Sub Main()
            Dim Sql As String = "SELECT UID,UNAME FROM USERTBL"
            Try
                  Using Conn As New SqlConnection
                        Conn.ConnectionString =
                                 ("Data Source=localhost\SQLEXPRESS;" &
                                    "Initial Catalog=sampleDB;" &
                                    "Integrated Security=SSPI;")
                        Conn.Open()
                        Using cmd As New SqlCommand(Sql)
                              cmd.Connection = Conn
                              cmd.CommandType = CommandType.Text
                              Using reader As SqlDataReader = cmd.ExecuteReader()
                                    While (reader.Read())
                                          Console.WriteLine(
                                                reader.GetInt32(0) &
                                                reader.GetString(1) 
                                    End While
                              End Using
                        End Using
                  End Using
            Catch ex As Exception
                  Console.WriteLine(ex.Message)
            End Try
      End Sub
End Module

 

VB.net

Posted by arkgame