更新SQL数据库
我有一个WinForm通过编辑两个TextBox产品名称和产品成本更新SQL数据库,但是它不更新数据库,这里是我的示例代码更新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)
,Porduct_Cost是bigint
。 任何想法我会感谢
首先,将字符串值转换成int
string cost = txtProductCost.Text;
costval=int.Parse(cost)// costval is integer
接下来,更新数据库
cmd.Parameters.AddWithValue("@Product_Price", costval);
它给了我一个例外“输入字符串的格式不正确。” – user2102572 2013-04-25 11:55:06
我认为这是bigInteger不是int – user2102572 2013-04-25 11:55:27
如果是这样,将其转换为正确的格式,并尝试 – 2013-04-25 11:57:29
看来你在转换一个错误,如果你的成本字段在数据库中是bigint,然后转换成
string cost = txtProductCost.Text
到
Int64 cost = Convert.Toint64(txtProductCost.Text);
Int64直接映射到BigInt。
或者如果它是双然后将其转换
string cost = txtProductCost.Text
到
Double cost = Convert.ToDouble(txtProductCost.Text);
希望它为你工作。
如果您使用Bigint然后使用Convert.Toint64而不是Convert.Toint32 – Rahul 2013-04-25 11:57:22
非常感谢你拉胡尔 – user2102572 2013-04-25 12:16:35
你有任何错误信息接收? – 2013-04-25 11:43:35
你得到的错误信息是什么,你在数据库中的成本是双倍或者是int数据类型。 – Rahul 2013-04-25 11:50:10
没有错误,它只是不起作用 – user2102572 2013-04-25 11:55:56