参数化查询需要没有提供的参数

我的代码有问题:

Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged list.Items.Clear() cmd.CommandText = "SELECT * FROM borrow where (Department LIKE '%" & TextBox2.Text & "%')" cmd.Connection = con cmd.CommandType = CommandType.Text con.Open() rd = cmd.ExecuteReader() If rd.HasRows = True Then While rd.Read() Dim listview As New ListViewItem listview.Text = rd("ID").ToString listview.SubItems.Add(rd("Department").ToString) listview.SubItems.Add(rd("Purpose").ToString) listview.SubItems.Add(rd("Items_Details").ToString) listview.SubItems.Add(rd("Requested_by").ToString) listview.SubItems.Add(rd("Approved_by").ToString) listview.SubItems.Add(rd("Date").ToString) listview.SubItems.Add(rd("Status").ToString) listview.SubItems.Add(rd("Date_Returned").ToString) list.Items.Add(listview) End While End If con.Close() 

一旦我在文本框中键入string来search一个项目,我得到这个错误:

参数化查询'(@ Parameter1 nvarchar(4000))SELECT * FROM borrow where(Departme'expect the parameter'@ Parameter1',which not not supplied。

谁能帮我?

如果将null值传递给参数,那么即使在添加参数后也会得到此错误,因此请尝试检查该值,如果为null,则使用DBNull.Value

这将工作

 cmd.Parameters.Add("@Department", SqlDbType.VarChar) If (TextBox2.Text = Nothing) Then cmd.Parameters("@Department").Value = DBNull.Value Else cmd.Parameters("@Department").Value = TextBox2.Text End If 

这会将空值从对象层转换为数据库可接受的DBNull值。

您的网站有被黑客攻击的危险。

阅读SQL注入以及如何在.NET中防止它

您的查询问题是您现在最担心的问题。

但…..

@ Misnomer的解决scheme是接近但不是那样:

将您的查询更改为:

 cmd.CommandText = "SELECT * FROM borrow where (Department LIKE '%@DepartmentText%')" 

并以这种方式添加参数(或@Misnomer所做的方式):

 cmd.Parameters.AddWithValue("@DepartmentText",TextBox2.Text) 

重要的区别是你需要改变你的CommandText。

尝试添加像这样的参数 –

 cmd.Parameters.Add("@Department", SqlDbType.VarChar) cmd.Parameters("@Department").Value = TextBox2.Text 

并把你的命令文本改成@Abe Miessler所做的一切,对,我只是想你会弄明白的。

 SqlConnection conn = new SqlConnection(connectionString); conn.Open(); //SelectCustomerById(int x); comboBoxEx1.Items.Clear(); SqlCommand comm = new SqlCommand("spSelectCustomerByID", conn); //comm.Parameters.Add(new SqlParameter("cust_name", cust_name)); //comm.CommandText = "spSelectCustomerByID"; comm.Parameters.Add(new SqlParameter("cust_id", SqlDbType.Int)); comm.CommandType = CommandType.StoredProcedure; comm.ExecuteNonQuery(); SqlDataAdapter sdap = new SqlDataAdapter(comm); DataSet dset = new DataSet(); sdap.Fill(dset, "cust_registrations"); if (dset.Tables["cust_registrations"].Rows.Count > 0) { comboBoxEx1.Items.Add("cust_registrations").ToString(); } comboBoxEx1.DataSource = dset; comboBoxEx1.DisplayMember = "cust_name";