简体   繁体   中英

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)

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. It also indicates that you are vulnerable to SQL injection attacks.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM