关于在设计SqlDataAdapter并使用带有参数的 SQL或存储过程时,出现的必须声明 @参数名 的错误解决方案
错误码代码如下:
Dim dbcon As New SqlConnection("Data Source=localhost;database=Northwind;Integrated Security=True")
Dim cmd As New SqlCommand("select * from Orders where OrderID=@ID", dbcon)
Dim para As New SqlParameter
With para
.ParameterName = "@ID"
.Direction = ParameterDirection.Input
.SqlDbType = SqlDbType.Int
.Value = TextBox1.Text
End With
cmd.Parameters.Add(para)
Dim adapter As New SqlDataAdapter(cmd.CommandText, dbcon) '错误
Dim dataset As New DataSet
adapter.Fill(dataset)
DataGridView1.DataSource = dataset.Tables(0)
错误提示如下:
正确代码如下:
Dim dbcon As New SqlConnection("Data Source=localhost;database=Northwind;Integrated Security=True")
Dim cmd As New SqlCommand("select * from Orders where OrderID=@ID", dbcon)
Dim para As New SqlParameter
With para
.ParameterName = "@ID"
.Direction = ParameterDirection.Input
.SqlDbType = SqlDbType.Int
.Value = TextBox1.Text
End With
cmd.Parameters.Add(para)
Dim adapter As New SqlDataAdapter(cmd)
Dim dataset As New DataSet
adapter.Fill(dataset)
DataGridView1.DataSource = dataset.Tables(0)
这其中只修改了一个地方,就是实例化 SqlDataAdapter对象的时候,Dim adapter As New SqlDataAdapter(cmd),而不是 Dim adapter As New SqlDataAdapter(cmd.CommandText, dbcon)
请注意:如下代码并没有错:
Dim dbcon As New SqlConnection("Data Source=localhost;database=Northwind;Integrated Security=True")
Dim cmd As New SqlCommand("select * from Orders where OrderID=@ID", dbcon)
Dim para As New SqlParameter
With para
.ParameterName = "@ID"
.Direction = ParameterDirection.Input
.SqlDbType = SqlDbType.Int
.Value = TextBox1.Text
End With
cmd.Parameters.Add(para)
dbcon.Open()
cmd.ExecuteNonQuery()