通过编辑c#文本框更新Sql数据库
本文关键字:更新 Sql 数据库 文本 编辑 | 更新日期: 2023-09-27 18:10:55
我有一个Winform通过编辑两个文本框Product Name和Product cost来更新SQL数据库,但是它不更新数据库,下面是我的示例代码
private void simpleButton5_Click(object sender, EventArgs e)
{
string id = comboBox2.Items[comboBox2.SelectedIndex].ToString();
string name = txtProdName.Text;
string cost = txtProductCost.Text;
cn.Open();
string query = "UPDATE [Product1] SET [Product_Name]= @Product_Name,[Product_Cost]= @Product_Cost where [Product_ID]= @Product_ID";
SqlCommand cmd = new SqlCommand(query, cn);
cmd.Parameters.AddWithValue("@Product_ID", id);
cmd.Parameters.AddWithValue("@Product_Name", name);
cmd.Parameters.AddWithValue("@Product_Price", cost);
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Update Succesfully");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
cn.Close();
}
id的数据类型为char
, Product_Name为nvarchar(50)
, product_cost为bigint
。如有任何想法,我将不胜感激
似乎你有一个错误的转换,如果你的成本字段在数据库是bigint然后转换
string cost = txtProductCost.Text
Int64 cost = Convert.Toint64(txtProductCost.Text);
Int64直接映射到BigInt。
或者如果是Double则转换为
string cost = txtProductCost.Text
Double cost = Convert.ToDouble(txtProductCost.Text);
首先,将字符串值转换为int
string cost = txtProductCost.Text;
costval=int.Parse(cost)// costval is integer
接下来,更新数据库
cmd.Parameters.AddWithValue("@Product_Price", costval);