我有一个查询来搜索我用来查找带有' IDnumber'的记录的数据库。在其'SportID'专栏也有' true'在其替代品#39;柱。但是,当涉及到执行此查询时,有时会抛出错误,表示存在语法错误,但在其他情况下(具有完全相同的用户输入),它不会丢弃错误。
错误是:
{"查询表达式中的语法错误(缺少运算符)' Substitute = true和SportID ='。"}
以下是代码:
OleDbConnection connection = new OleDbConnection(Connection string is here);
OleDbCommand command = new OleDbCommand();
// this part of the query determines whether there is a substitute in the sport or not
connection.Open();
command.Connection = connection;
command.CommandText = "Select * FROM [Sport] WHERE Substitute = true and SportID = " + Form1.IDNumber;
if (command.ExecuteScalar() != null)
{
substituteInSport = true;
}
else
{
substituteInSport = false;
}
connection.Close();
我不确定该怎么办,因为我无法弄清楚是什么让它说有错误。任何帮助将不胜感激。
答案 0 :(得分:1)
您应该使用参数化查询 - 使用正确的数据类型!
假设列SportID
是f类型Integer
,它将如下所示:
using (OleDbConnection connection = new OleDbConnection("the_connection_string"))
using(OleDbCommand command = new OleDbCommand())
{
// this part of the query determines whether there is a substitute in the sport or not
connection.Open();
command.Connection = connection;
command.CommandText = "Select * FROM [Sport] WHERE Substitute = true and SportID = ?";
command.Parameters.Add("@p1", OleDbType.Integer).Value = Convert.ToInt32(Form1.IDNumber);
if (command.ExecuteScalar() != null)
substituteInSport = true;
else
substituteInSport = false;
}
答案 1 :(得分:0)
正如@CeInSql建议你应该使用参数化查询来阻止SQL注入。您还需要从SportID
获取Form1
的值,例如,如果IDNumber
文本框,您从中获取值,请使用Form1.IDNumber.Text
获取来自用户控制的价值。
using (OleDbConnection connection = new OleDbConnection("the_connection_string"))
using(OleDbCommand command = new OleDbCommand())
{
// this part of the query determines whether there is a substitute in the sport or not
connection.Open();
command.Connection = connection;
command.CommandText = "Select * FROM [Sport] WHERE Substitute = true and SportID = ?";
command.Parameters.Add("@p1", OleDbType.Integer).Value = Convert.ToInt32(Form1.IDNumber.Text);
if (command.ExecuteScalar() != null)
substituteInSport = true;
else
substituteInSport = false;
}