[英]Syntax Error when executing OLEDB Select statement
When I run this query I get the following error: 当我运行此查询时,出现以下错误:
Syntax error(missing operator) in query expression '[Customer] = 'O'SMILE' and [Product] = 'Casserole(20kg) 查询表达式'[客户] ='O'SMILE'和[产品] ='砂锅(20kg)中的语法错误(缺少运算符)
Code: 码:
// When print button is executed database operations
// Load data from database based upon select query
String codeQuery = "SELECT count(*) FROM [sheet1$] WHERE [Customer] = '" + lblcustomername.Text + "' and [Product]='" + lblproductname.Text + "'";
OleDbConnection Connection;
Connection = new OleDbConnection(OutputDatabaseConnectionString);
OleDbCommand Command = new OleDbCommand(codeQuery, Connection);
Command.Connection = Connection;
try
{
Connection.Open();
count = (Int32)Command.ExecuteScalar();
Connection.Close();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
The error is because of the unquoted single quote "'" in the name O'SMILE
and your use of string concatenation, rather than using a parameterised query. 该错误是因为名称O'SMILE
中的单引号“'”未加引号,以及您使用字符串串联而不是使用参数化查询。 It also indicates that you are vulnerable to SQL injection attacks. 它还表明您容易受到SQL注入攻击的攻击。
You must use Parameters! 您必须使用参数!
string sql = "SELECT count(*) FROM [sheet1$] WHERE [Customer] = @customer and [Product] = @product";
using (SqlConnection connection = new SqlConnection(/* connection info */))
using (SqlCommand command = new SqlCommand(sql, connection))
{
cmd.Parameters.Add("customer", SqlDbType.VarChar, 100).Value = lblcustomername.Text;
cmd.Parameters.Add("product", SqlDbType.VarChar, 120).Value = lblproductname.Text;
count = (Int32)command.ExecuteScalar();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.