尝试从 Access 数据库中搜索时出现 C#OleDb 异常“没有为一个或多个必需参数提供值”[关闭]
Posted
技术标签:
【中文标题】尝试从 Access 数据库中搜索时出现 C#OleDb 异常“没有为一个或多个必需参数提供值”[关闭]【英文标题】:C# OleDb Exception “No value given for one or more required parameters” while trying to search from Access database [closed] 【发布时间】:2021-05-28 01:22:44 【问题描述】:我正在尝试使用 Windows 窗体应用程序在 Access 数据库中搜索输入值,找到的结果应显示在文本框中。但我不断收到此错误。
这是我的代码:
private void btn_search_Click(object sender, EventArgs e)
string search = "";
SearchForm popup = new SearchForm();
DialogResult dialogresult = popup.ShowDialog();
if (dialogresult == DialogResult.OK)
search = SearchForm.item;
if (search != "")
Access_Connections.sql = "SELECT * FROM Learners WHERE @val IN(ID, Learner_name, Learner_surname, Grade, School, Gender, Blood_group, Home_language, Church_relation, Hostel_block);";
Access_Connections.cmd.Parameters.AddWithValue("@val", search);
Access_Connections.cmd.Parameters.Clear();
Access_Connections.cmd.CommandType = CommandType.Text;
Access_Connections.cmd.CommandText = Access_Connections.sql;
Access_Connections.cmd.Connection = Access_Connections.con;
Access_Connections.openConnection();
Access_Connections.rd = Access_Connections.cmd.ExecuteReader();
while (Access_Connections.rd.Read())
text_name.Text += Access_Connections.rd["Learner_name"].ToString();
text_surname.Text += Access_Connections.rd["Learner_surname"].ToString();
text_grade.Text += Access_Connections.rd["Grade"].ToString();
text_school.Text += Access_Connections.rd["School"].ToString();
Access_Connections.closeConnection();
else if (dialogresult == DialogResult.Cancel)
Console.WriteLine("You clicked either Cancel or X button in the top right corner");
popup.Dispose();
【问题讨论】:
你添加参数,然后立即清除参数... 您的连接字符串有问题。 另外:如果抛出异常,closeConnection()
函数将不会运行,从而使数据库文件锁定打开。将连接放在using
块内!
【参考方案1】:
你把它颠倒了:
"SELECT * FROM Learners WHERE (Learner_name=@val OR Learner_surname=@val OR Grade=@val OR School=@val OR Gender=@val OR Blood_group=@val OR Home_language=@val OR Church_relation=@val OR Hostel_block=@val);"
【讨论】:
以上是关于尝试从 Access 数据库中搜索时出现 C#OleDb 异常“没有为一个或多个必需参数提供值”[关闭]的主要内容,如果未能解决你的问题,请参考以下文章
从 Java 连接到 SQL Server 2016 时出现 EXCEPTION_ACCESS_VIOLATION
从 Access 数据库中读取字段时出现 IndexOutOfRangeException