查询表达式中的语法错误(缺少运算符)

时间:2017-08-22 07:13:32

标签: c# winforms

我正在使用c#,这个错误让我感到头疼。我不知道如何解决这个错误。 任何人都可以帮我解决这个问题。这是代码

try
{
    string MyConnection2 = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\DELL\Documents\db1.mdb";
    //Display query  
    string Query = "select  riq_num , department, item_name , item_unit , no_of_stock_out , itemtype from outputdet1 where riq_num = " + textBox2.Text + " or department= '" + comboBox1.Text + " ' or item_name= '" + textBox4.Text + "' or item_unit= '" + comboBox2.Text + "' or no_of_stock_out = " + textBox6.Text + " or itemtype = '" + comboBox3.Text + "' ; ";

    OleDbConnection MyConn2 = new OleDbConnection(MyConnection2);
    OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2);
    MyConn2.Open();

    //For offline connection we will use  MySqlDataAdapter class.  
    OleDbDataAdapter MyAdapter = new OleDbDataAdapter();
    MyAdapter.SelectCommand = MyCommand2;
    DataTable dTable = new DataTable();
    MyAdapter.Fill(dTable);

    // here i have assign dTable object to the dataGridView1 object to display data.         
    dataGridView1.DataSource = dTable;       
    MyConn2.Close();
}
    // OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2);
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

1 个答案:

答案 0 :(得分:4)

我认为textBox2.Text& textBox6.Text从文本框控件返回一个字符串,以便OleDbCommand在包含空值或任何非数字字符串时抛出异常,因为它将形成无效的SQL语句。使用参数化查询,如下例所示:

string Query = @"select riq_num, department, item_name, item_unit, no_of_stock_out, itemtype 
                 from outputdet1 
                 where riq_num = @riq_num
                 or department= @department 
                 or item_name= @item_name
                 or item_unit= @item_unit
                 or no_of_stock_out = @no_of_stock_out 
                 or itemtype = @itemtype";

using (OleDbConnection MyConn2 = new OleDbConnection(MyConnection2))
{
    using (OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2))
    {
        MyConn2.Open();

        MyCommand2.Parameters.Add("@riq_num", textBox2.Text);
        MyCommand2.Parameters.Add("@department", comboBox1.Text);
        MyCommand2.Parameters.Add("@item_name", textBox4.Text);
        MyCommand2.Parameters.Add("@item_unit", comboBox2.Text);
        MyCommand2.Parameters.Add("@no_of_stock_out", textBox6.Text);
        MyCommand2.Parameters.Add("@itemtype", comboBox3.Text);

        // execute the query here
    }
}

请记住,using语句在关闭后立即用于处理OLEDB连接,以便GC可以释放资源。

附加说明:

OleDbParameter使用参数顺序而不是命名参数,因此确保参数从头到尾以正确的顺序声明