语法执行OLEDB Select语句时出错

时间:2018-03-10 04:55:22

标签: c# ado.net oledb parameterized-query

当我运行此查询时,我收到以下错误:

  

查询表达式中的语法错误(缺少运算符)' [客户] =' O' SMILE'和[产品] ='砂锅(20公斤)

代码:

// 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());
}

1 个答案:

答案 0 :(得分:2)

错误是因为单引号不引用"'"""在名称O'SMILE中使用字符串连接,而不是使用参数化查询。它还表明您容易受到SQL注入攻击。

您必须使用参数!

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();
}