简体   繁体   English

执行OLEDB Select语句时的语法错误

[英]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.

相关问题 UPDATE语句中的语法错误OleDb异常 - Syntax error in UPDATE statement OleDb Exception C#oledb中的INSERT INTO语句中的语法错误? - Syntax error in INSERT INTO statement in c# oledb? 使用OleDb的INSERT INTO语句中的语法错误 - Syntax error in INSERT INTO statement using OleDb INSERT INTO语句中的语法错误。/Excel/oledb - Syntax error in INSERT INTO statement./Excel/oledb 使用此INSERT INTO语句和.NET OleDb命名空间时,如何解决语法错误? - How to solve a syntax error when using this INSERT INTO statement and the .NET OleDb namespace? 将带有图像的详细信息保存在表中时,INSERT INTO 语句中的语法错误会在 OleDb 未处理的情况下弹出 - SYNTAX ERROR IN INSERT INTO statement pops in with OleDb unhandled when saving details with image in a table 查询表达式Oledb INSERT语句中的语法错误(缺少运算符) - Syntax error (missing operator) in query expression, Oledb INSERT Statement C#中UPDATE语句OleDb异常中的语法错误 - Syntax error in UPDATE statement OleDb Exception in C# System.Data.OleDb.OleDbException:INSERT INTO语句中的语法错误 - System.Data.OleDb.OleDbException: Syntax error in INSERT INTO statement System.Data.OleDb.OleDbException: 'UPDATE 语句中的语法错误。 ' - System.Data.OleDb.OleDbException: 'Syntax error in UPDATE statement. '
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM