简体   繁体   中英

+1 to data column using SQL Server Compact 4.0

I am trying to create a simple button, that when clicked, adds 1 to the related column. I use a dropdown box to select the ID, then add 1 to the value. However, I am presented with the error:

A first chance exception of type 'System.Data.SqlServerCe.SqlCeException' occurred in System.Data.SqlServerCe.dll

and it highlights cm.ExecuteNonQuery();

I have gone through several attempts at this but it's getting me a little confused as to why I can't simply run the SQL statement.

Here is the code

private void button2_Click(object sender, EventArgs e) {
    try {
        SqlCeCommand cm = new SqlCeCommand("UPDATE fixedBugs SET Success = Success + 1 WHERE Fixed_ID = '" + comboBox1.Text, mySqlConnection);
        cm.ExecuteNonQuery();
    } catch (SqlCeException) {
        MessageBox.Show("Error");
    }
}

Your command has a opening apostrophe which is not being closed. This should fix it.

SqlCeCommand cm = new SqlCeCommand("UPDATE fixedBugs SET Success = Success + 1 WHERE Fixed_ID = '" + comboBox1.Text + "'", mySqlConnection);

But that's a security issue since the user can manage to add extra commands to your query, which could ruin your entire database.

This is a better solution since using parameters is more safe.

SqlCeCommand cm = new SqlCeCommand("UPDATE fixedBugs SET Success = Success + 1 WHERE Fixed_ID = @fixedid;", mySqlConnection);
cm.Parameters.AddWithValue("@fixedid", comboBox1.Text);

This will prevent future headaches.

This question has better detailed answers that may help enlighten your mind...

"UPDATE fixedBugs SET Success = Success + 1 WHERE Fixed_ID = '" + comboBox1.Text + "'"

是否需要在查询中使用'关闭字符串参数?

You need to think about below things;

  1. User must select a value.
  2. Security
  3. Dispose the command after using it.

      string selectedValue = comboBox1.Text; if (string.IsNullOrEmpty(selectedValue)) { MessageBox.Show("Please select something"); return; } string sql = "UPDATE fixedBugs SET Success = ISNULL(Success,0) + 1 WHERE Fixed_ID = @selectedValue"; try { using (SqlCeCommand cm = new SqlCeCommand(sql, mySqlConnection)) { SqlCeParameter param = new SqlCeParameter("@selectedvalue", SqlDbType.NText); cm.Parameters.Add(param); cm.Parameters["@selectedvalue"].Size = 50; cm.Parameters["@selectedvalue"].Value = selectedValue.Trim(); cm.ExecuteNonQuery(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } 

PS: Code is not tested.

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