没有为一个或多个必需参数指定值.搜索时出错 [英] No value given for one or more required parameters. error during Search
问题描述
我正在尝试在一个简单的访问数据库中搜索数据.代码是这样的
I am trying to search the data in a simple access database. The code is this
Call connect()
con.Open()
cmd = New OleDbCommand("Select * from PO_Record_Table where Customer=asd", con)
dr = cmd.ExecuteReader
While dr.Read
MsgBox(dr(1))
End While
con.Close()
如果我按下搜索按钮,则会出现错误:没有为一个或多个必需参数提供值就在这条线上
If I press search button, the error: No value given for one or more required parameters comes on this line
dr = cmd.ExecuteReader
记录asd"作为文本类型位于数据库客户字段中.为什么会出现这个错误,如何在没有错误的情况下完成这个搜索?
The record "asd" is in the database customer field as a text type. Why does this error come and how to finish this search without error?
推荐答案
我想错误在于文本 asd
作为客户名称的值传递
I suppose that the error is in the text asd
passed as value for the customer name
cmd = New OleDbCommand("Select * from PO_Record_Table where Customer='asd'", con)
将它放在单引号中允许数据库引擎将其识别为字符串值以检查 Customer
列名称.如果没有引号,它会被解释为您尚未传递给命令的参数的名称.
Putting it in single quotes allows the db engine to recognize it as a string value to check against the Customer
column name. Without quotes it is interpreted as the name of a parameter that you haven't passed to the command.
EDIT 在下面的评论中,您尝试将文本框的内容作为 Customer 列的值传递,但您忘记在文本框文本值周围添加引号.
EDIT In your comment below you try to pass, as value for the Customer column, the content of a textbox but you forget to add the quotes around your textbox text value.
cmd = New OleDbCommand("Select * from PO_Record_Table where Customer='" & textbox.text & "'", con)
然而,这不应该使用字符串连接方法来完成,而总是使用参数化方法
However, this should never be done using the string concatenation method, but always with the parameterized approach
cmd = New OleDbCommand("Select * from PO_Record_Table where Customer=@custName", con)
cmd.Parameters.AddWithValue("@custName", Txt_Find.Text)
dr = cmd.ExecuteReader
.....
这是查询传递命令文本的数据库的唯一好方法,该命令文本包含用户输入获得的值.这种方法可以让您的代码免受 SQL 注入攻击 并消除解析文本框内容的问题.事实上,如果没有参数并且您的文本框包含单引号,则字符串连接方法将因语法错误而失败.
This is the only good method to query a database passing a command text with values obtained by user input. This method allows your code to be safe from SQL Injection attacks and remove problems in parsing the content of the textbox. Infact, without a parameter and if your textbox contains a single quote, the string concatenation method would fail with a syntax error.
这篇关于没有为一个或多个必需参数指定值.搜索时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!