C# OleDb Exception “No value given for one or more required parameters” while trying to delete from Access database

为君一笑 提交于 2019-12-01 17:42:55

Include the quotes around the value you get from this.textBox2.Text as in your working sample query.

" AND Subject = '" + this.textBox2.Text + "';";

Imagine this.textBox2.Text contains the text foo. Without adding those quotes in the WHERE clause the db engine would see ... WHERE Semester = 1 AND Subject = foo But it can't find anything in the data source named foo, so assumes it must be a parameter. You need the quotes to signal the db engine it's a string literal value, 'foo'.

Actually if you switch to a parameter query, you can avoid this type of problem because you won't need to bother with those quotes in the DELETE statement. And a parameter query will also safeguard you against SQL injection. If a malicious user can enter ' OR 'a' = 'a in this.textBox2.Text, all rows in the table would be deleted.

If you got a same error for "insert" query you can use this method for avoid exception

string sqlQuery = "INSERT into EndResultOfTestCases(IDsOfCases,TestCaseName,ResultCase,ResultLog) VALUES(@ids, @casename, @results, @logs)";

        connection = new OleDbConnection(connectionStringToDB);
        command = new OleDbCommand(sqlQuery, connection);
        command.Parameters.AddWithValue("@ids",IDs);
        command.Parameters.AddWithValue("@casename", CaseName);
        command.Parameters.AddWithValue("@results", resultOfCase);
        command.Parameters.AddWithValue("@logs", logs);
        connection.Open();
        command.ExecuteNonQuery();
        connection.Close();
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!