「VB.NET」SQLServerに接続するサンプル
書式
Using Conn As New SqlConnection
Conn.ConnectionString ="DB接続情報"
Conn.Open()
Using cmd As New SqlCommand(SQL構文)
Using reader As SqlDataReader = cmd.Executereader()
処理機コード
End Using
Using Conn As New SqlConnection
Conn.ConnectionString ="DB接続情報"
Conn.Open()
Using cmd As New SqlCommand(SQL構文)
Using reader As SqlDataReader = cmd.Executereader()
処理機コード
End Using
Using Conn As New SqlConnection Conn.ConnectionString ="DB接続情報" Conn.Open() Using cmd As New SqlCommand(SQL構文) Using reader As SqlDataReader = cmd.Executereader() 処理機コード End Using
使用例
Imports System.Data.SqlClient
Module Module1
Sub Main()
'SQL構文
Dim Sql As String = "SELECT USERNAME,ADDR FROM USERTBL"
Try
Using Conn As New SqlConnection
'サーバー名とデータベース名を指定
Conn.ConnectionString = ("Data Source=xxx;" & "Initial Catalog=xxx;" & "Integrated Security=SSPI;")
'データベースに接続
Conn.Open()
'usingステートメント
Using cmd As New SqlCommand(Sql)
cmd.Connection = Conn
cmd.CommandType = CommandType.Text
'SQL構文を実行
Using reader As SqlDataReader = cmd.ExecuteReader()
While (reader.Read())
'テーブルから取得カラムの値を表示
Console.WriteLine(reader.GetString(0) & reader.GetString(1))
End While
End Using
End Using
End Using
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Console.ReadKey()
End Sub
End Module
Imports System.Data.SqlClient
Module Module1
Sub Main()
'SQL構文
Dim Sql As String = "SELECT USERNAME,ADDR FROM USERTBL"
Try
Using Conn As New SqlConnection
'サーバー名とデータベース名を指定
Conn.ConnectionString = ("Data Source=xxx;" & "Initial Catalog=xxx;" & "Integrated Security=SSPI;")
'データベースに接続
Conn.Open()
'usingステートメント
Using cmd As New SqlCommand(Sql)
cmd.Connection = Conn
cmd.CommandType = CommandType.Text
'SQL構文を実行
Using reader As SqlDataReader = cmd.ExecuteReader()
While (reader.Read())
'テーブルから取得カラムの値を表示
Console.WriteLine(reader.GetString(0) & reader.GetString(1))
End While
End Using
End Using
End Using
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Console.ReadKey()
End Sub
End Module
Imports System.Data.SqlClient Module Module1 Sub Main() 'SQL構文 Dim Sql As String = "SELECT USERNAME,ADDR FROM USERTBL" Try Using Conn As New SqlConnection 'サーバー名とデータベース名を指定 Conn.ConnectionString = ("Data Source=xxx;" & "Initial Catalog=xxx;" & "Integrated Security=SSPI;") 'データベースに接続 Conn.Open() 'usingステートメント Using cmd As New SqlCommand(Sql) cmd.Connection = Conn cmd.CommandType = CommandType.Text 'SQL構文を実行 Using reader As SqlDataReader = cmd.ExecuteReader() While (reader.Read()) 'テーブルから取得カラムの値を表示 Console.WriteLine(reader.GetString(0) & reader.GetString(1)) End While End Using End Using End Using Catch ex As Exception Console.WriteLine(ex.Message) End Try Console.ReadKey() End Sub End Module