参数化查询Visual Basic

时间:2015-09-06 14:48:40

标签: sql sql-server vb.net parameters

我一直无法让参数化查询工作。没有参数化的SQL,代码工作正常。

我得到的错误是Must declare the scalar variable @RegNo

Dim conn As New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\dbsBank.mdf;Integrated Security=True")

Dim queryString As String = "SELECT PAC FROM Customers WHERE Registration_No = @RegNo"

Dim cmd As New SqlCommand(queryString, conn)
Dim param As SqlParameter = New SqlParameter("@RegNo", SqlDbType.Int)
param.Value = mtbPassword.Text
cmd.Parameters.Add(param)

Dim adap As New SqlDataAdapter(queryString, conn)

dTable = New DataTable

Try
    adap.Fill(dTable)
Catch ex As Exception
    MessageBox.Show(ex.Message)
End Try

1 个答案:

答案 0 :(得分:4)

您构建了Command对象但从未使用过它。所以你的DataAdapter永远不会有参数定义。

替换

Dim adap As New SqlDataAdapter(queryString, conn)

Dim adap As New SqlDataAdapter(cmd)

这最有可能解决您的问题