0

私は Visual Studio の初心者で、ユーザーがクエリに値を入力できるようにしたい

つまり、使用する従業員を検索します

Select * From Employee Where ID = (i want the user to enter the value here)

既にデータベースに接続しており、テキスト ボックスから値を取得できることはわかっていますが、その値をクエリに直接入力してすぐに呼び出す方法がわかりません。

4

1 に答える 1

1

パラメータ化は比較的簡単です。

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    ExecuteSQL("Data Source=Server;Initial Catalog=Database;Persist Security Info=True;Integrated Security=True", _
               "Select * From Employee Where ID=@id",
               New SqlClient.SqlParameter("@id", 123))
End Sub

Public Function ExecuteSQL(ByVal Connection As String, _
                      ByVal SQL As String, _
                      ByRef Param As SqlClient.SqlParameter) As System.Data.DataTable
    Try
        Dim dt As System.Data.DataTable = Nothing
        Dim SqlRdr As SqlClient.SqlDataReader

        Using SqlConn As SqlClient.SqlConnection = New SqlClient.SqlConnection(Connection)
            Using SqlCmd As SqlClient.SqlCommand = New SqlClient.SqlCommand(SQL, SqlConn)
                SqlCmd.CommandType = CommandType.Text
                SqlCmd.Parameters.Add(Param)
                SqlConn.Open()
                SqlRdr = SqlCmd.ExecuteReader()
                Try
                    If SqlRdr.IsClosed = False AndAlso SqlRdr.HasRows = True Then
                        dt = New System.Data.DataTable
                        dt.BeginLoadData()
                        dt.Load(SqlRdr)
                        dt.EndLoadData()
                    End If
                Finally
                    If SqlRdr IsNot Nothing Then
                        SqlRdr.Close()
                    End If
                End Try
            End Using
        End Using

        Return dt
    Catch ex As Exception
        Return Nothing
    End Try
End Function
于 2012-02-01T16:17:32.070 に答える