未处理OleDbException:语法错误(缺少运算符)在查询表达式中

时间:2011-11-24 07:09:10

标签: c# database visual-studio-2010 ms-access-2007 oledb

我是使用Visual Stuido 2010 C#和Microsft Access 2007创建应用程序的新手。我打算创建一个用户可以向数据库添加数据的应用程序(MS-Access)。但是我收到一条错误,指出“语法错误(缺少运算符)在查询表达式中”。我真的找不到我的代码有什么问题。

这是我向数据库添加数据的代码:

private void buttonSaveFuelLimit_Click(object sender, EventArgs e)
    {
        string MyConString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\KKKKK\Documents\Visual Studio 2010\Projects\Trial\Trial\gxi.accdb";
        OleDbConnection connection = new OleDbConnection(MyConString);
        OleDbCommand command = connection.CreateCommand();
        command.Connection = connection;
        using (OleDbConnection conn = new OleDbConnection(MyConString))
        {
            connection.Open();
            using (OleDbCommand com = connection.CreateCommand())
            {
                command.CommandText = "insert into fuel_limit(fuel_limit_code, fuel_limit_description) values(?fuel_limit_code, ?fuel_limit_description)";
                command.Parameters.Add(new OleDbParameter("?fuel_limit_code", OleDbType.VarChar));
                command.Parameters.Add(new OleDbParameter("?fuel_limit_description", OleDbType.VarChar));
                command.Parameters["?fuel_limit_code"].Value = textBoxFuelLimitCode.Text;
                command.Parameters["?fuel_limit_description"].Value = textBoxFuelLimitDesc.Text;
                command.ExecuteNonQuery();
                MessageBox.Show("Data Saved");
            }
        }
    }

这是错误消息的屏幕截图: enter image description here

2 个答案:

答案 0 :(得分:4)

您需要插入到语句中的值部分。

插入fuel_limit(fuel_limit_code,fuel_limit_description)值(?fuel_limit_code,?fuel_limit_description)

此外,在ExecuteNonQuery语句正上方的行中设置值时,您似乎需要使用description参数。

答案 1 :(得分:1)

---编辑答案--- 以下工作


command.CommandText = "insert into fuel_limit(fuel_limit_code, fuel_limit_description) values(?, ?)";
command.Parameters.AddWithValue(new OleDbParameter("@fuel_limit_code",textBoxFuelLimitCode.Text));
command.Parameters.AddWithValue(new OleDbParameter("@fuel_limit_desc", textBoxFuelLimitDesc.Text));
command.ExecuteNonQuery();


---旧答案---

这是需要修正的行


command.CommandText = "insert into fuel_limit(fuel_limit_code, fuel_limit_description)";
//should ne
command.CommandText = "insert into fuel_limit(fuel_limit_code, fuel_limit_description) values(?,?)";