解析C#错误查询

时间:2015-12-05 18:47:08

标签: c# sql sql-server-ce

  

System.Data.SqlServerCeException(0x80004005):解析查询时出错。 [令牌行号= 1,令牌行偏移= 120,令牌错误= @price]

我在运行程序时遇到这个错误,我无法弄清楚我做错了什么。我已经尝试过多次改变它并且它一直给出相同的错误,只是“令牌行偏移=”有时改变后的数字。

static public void Insert(string _id, string _city, string _state, string _country, int _beds, int _baths, int _price)
{
        try
        {
            connection.Open();
            SqlCeCommand commandInsert = new SqlCeCommand("INSERT INTO [House] (id, city, state, country, beds, baths, price) VALUES (@id, @city, @state, @country, @beds, @baths, @price", connection);
            commandInsert.Parameters.AddWithValue("@id", _id);
            commandInsert.Parameters.AddWithValue("@city", _city);
            commandInsert.Parameters.AddWithValue("@state", _state);
            commandInsert.Parameters.AddWithValue("@country", _country);
            commandInsert.Parameters.AddWithValue("@beds", _beds);
            commandInsert.Parameters.AddWithValue("@baths", _baths);
            commandInsert.Parameters.AddWithValue("@price", _price);
            commandInsert.ExecuteNonQuery();
        }
        catch (SqlCeException exception)
        {
            MessageBox.Show(exception.ToString());
        }
        finally
        {
            connection.Close();
        }
}

按钮内的代码

private void btn_insert_Click(object sender, EventArgs e)
{
        if (txt_id.Text != "" && txt_city.Text != "" && txt_state.Text != "" && txt_country.Text != "")
        {
            SQLFunctions.Insert(txt_id.Text, txt_city.Text, txt_state.Text, txt_country.Text, int.Parse(txt_beds.Text), int.Parse(txt_baths.Text), int.Parse(txt_Price.Text));
            SQLFunctions.Refresh(this.dataGridView1);
        }
}

2 个答案:

答案 0 :(得分:3)

我认为您忘记在VALUES(参数后使用)关闭@price部分。

VALUES (@id, @city, @state, @country, @beds, @baths, @price)

还有一些事情;

答案 1 :(得分:0)

试试这个

query="INSERT INTO [House] (id, city, state, country, beds, baths, price) VALUES ('@id', '@city', '@state', '@country', '@beds', '@baths', '@price')";

并用此

替换您的try
 connection.Open();
            SqlCeCommand commandInsert = new SqlCeCommand(query, connection);
            commandInsert.Parameters.AddWithValue("id", _id);
            commandInsert.Parameters.AddWithValue("city", _city);
            commandInsert.Parameters.AddWithValue("state", _state);
            commandInsert.Parameters.AddWithValue("country", _country);
            commandInsert.Parameters.AddWithValue("beds", _beds);
            commandInsert.Parameters.AddWithValue("baths", _baths);
            commandInsert.Parameters.AddWithValue("price", _price);
            commandInsert.ExecuteNonQuery();