1

I'm working with MS Access and would like to how to update the data correctly..here is the code i use on my button click event with no luck

OleDbCommand cmd = new OleDbCommand("SELECT * FROM ItemTemp WHERE ITEM='" + txtItemname.Text + "'", GetConnection());
OleDbDataReader reader = cmd.ExecuteReader();

//check if this item exist on the table ItemTemp
if (reader.HasRows == true)
{
    // item exists, do below action
    OleDbCommand cmde = new OleDbCommand("UPDATE ItemTemp SET QUANTITY=QUANTITY + @QUANTITY, PRICE=PRICE + @PRICE WHERE ITEM='" + txtItemname.Text + "'", GetConnection());
    cmde.Parameters.AddWithValue("@QUANTITY", txtItemquantity.Value); //numericupdown control
    cmde.Parameters.AddWithValue("@PRICE", txtItemprice.Text); //textbox control
    cmde.ExecuteNonQuery();
}

data on database BEFORE updating:

ID    |    ITEM    |    QUANTITY    |    PRICE
1     |    ITEM1   |        1       |    400

data on database AFTER updating:

ID    |    ITEM    |    QUANTITY    |    PRICE
1     |    ITEM1   |       11       |    400400

data on database which i want it to be AFTER updating:

ID    |    ITEM    |    QUANTITY    |    PRICE
1     |    ITEM1   |        2       |    800

i do believe my command is correct if not my bad..there's no other than this code on my button click event. any ideas?

4

2 回答 2

1

好的,现在似乎完成了。我只是改变

cmde.Parameters.AddWithValue("@QUANTITY", txtItemquantity.Value); //numericupdown control
cmde.Parameters.AddWithValue("@PRICE", txtItemprice.Text); //textbox control

对此

cmde.Parameters.AddWithValue("@QUANTITY", Convert.ToInt32(txtItemquantity.Value));
cmde.Parameters.AddWithValue("@PRICE", Convert.ToInt32(txtItemprice.Text));
于 2013-03-13T20:47:41.450 回答
1

首先,您应该确保数据库字段 Quantity 和 Price 是数字类型。如果它们是文本,那么您的查询会将作为参数传递的字符串值与数据库列中存在的字符串连接起来。

其次,当您使用 AddWithValue 传递参数时,框架会为您推断数据类型以查看传递值的数据类型。在您的情况下,您传递一个字符串,并且数据库引擎会看到一个将连接到现有值的字符串。您需要在传递到适当的数据类型之前进行转换

最后,对传递给数据库引擎的每一件事都使用 allways 参数化查询,特别是如果传递的值来自输入文本框。

 OleDbCommand cmd = new OleDbCommand("SELECT * FROM ItemTemp WHERE ITEM=@item", GetConnection());
 cmd.Parameters.AddWithValue("@item", txtItemName.Text);
 OleDbDataReader reader = cmd.ExecuteReader();

 //check if this item exist on the table ItemTemp
 if (reader.HasRows == true)
 {
     OleDbCommand cmde = new OleDbCommand("UPDATE ItemTemp SET QUANTITY=QUANTITY + @QUANTITY," + 
     "PRICE=PRICE + @PRICE WHERE ITEM=@item, GetConnection());
     cmde.Parameters.AddWithValue("@QUANTITY", Convert.ToInt32(txtItemquantity.Value)); 
     cmde.Parameters.AddWithValue("@PRICE", Convert.ToDecimal(txtItemprice.Text)); 
     cmde.Parameters.AddWithValue("@item", txtItemName.Text);
     cmde.ExecuteNonQuery();
 }
于 2013-03-13T20:50:50.563 回答