SELECT 文の結果をSqlDataReaderを用いて取得する方法を説明します。

SqlDataReaderによる取得

Dim builder As SqlConnectionStringBuilder = New SqlConnectionStringBuilder()
builder.DataSource = ".\SQLEXPRESS"
builder.AttachDBFilename = "D:\DB\TestDB.mdf"
builder.IntegratedSecurity = True
builder.UserInstance = True
builder.MultipleActiveResultSets = True
Dim ConnectString As String = builder.ToString()

Using sqlConnect As New SqlConnection(ConnectString)
    sqlConnect.Open()

    Dim command As SqlCommand = sqlConnect.CreateCommand()

    Try
        command.CommandText = "SELECT * FROM Table_1"
        Dim dtReader As SqlDataReader = command.ExecuteReader()

        Dim s As String = ""
        While (dtReader.Read())
            s &= dtReader("Item2").ToString()
            s &= System.Environment.NewLine
        End While
        dtReader.Close()
       
        MessageBox.Show(s)
    Catch ex As Exception
    End Try
End Using

 

エスケープ処理

LINKを使用するときは、エスケープ処理をする必要があります。

Public Function LikeEscape(str As String) As String
    Return str.Replace("[", "[[]").Replace("%", "[%]").Replace("_", "[_]")
End Function