简体   繁体   中英

Getting a syntax error (missing operator) in query expression in C#

I am writing a code and getting a syntax error that I dont know from where that comes. This is the code I am using:

string u = "select uniqcode from login where users='" + textBoxX1.Text + "' ";

and this is the error I am getting:

"Syntax error (missing operator) in query expression ''select uniqcode from login where users='someuser' ''." (System.Data.OleDb.OleDbException)A System.Data.OleDb.OleDbException was thrown: "Syntax error (missing operator) in query expression ''select uniqcode from login where users='someuser' ''."

It might be possible that textbox text is containing single quote ('). If yes then replace single quote (') by two single quotes ('')

Otherwise, try to execute it using sql parameters.

string u = "select login.uniqcode from [login] where users='" + textBoxX1.Text.Trim() + "'";

Since your error represent that you are using OleDb connection then you may use following code. This will avoid SQL Injection as well. However you may need to work a bit to following piece into your code.

u = "select uniqcode from login where users=?"; 

u.Parameters.Add("@users", OleDbType.VarChar).value = textBoxX1.Text;

You may see examples here and here

You need to firstly read and understand there are SQL syntax limitations in OleDB.

"A single quote must be escaped with another single quote."

But really, forget single quotes.

Read more about using OleDB here . It's ancient technology anyway, so I would get away from OleDB and have your database ported over to SQL Server or MySQL.

However, what you may need is something like this...

try
{
    connw.Open();
    OleDbCommand command;
    command = new OleDbCommand(
        "SELECT *" +
        "FROM tableA WHERE Deliveries.EmployeeID = ?, Deliveries.FIN = ?, Deliveries.TodaysOrders = ? , connw);
    command.Parameters.Add(new OleDbParameter("@EMPID", Convert.ToDecimal(empsplitIt[1])));
    command.Parameters.Add(new OleDbParameter("@FIN", truckSplit[1].ToString()));
    command.Parameters.Add(new OleDbParameter("@TodaysOrder", "R"));
    catchReturnedRows = command.ExecuteNonQuery();//Commit   
    connw.Close();

}
catch (OleDbException exception)
{
    MessageBox.Show(exception.Message, "OleDb Exception");
}

Golden rule of database coding, is never pass a variable directly into the SQL statement like you've done above. That is opening yourself for SQL Injection big time.

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