[英]Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll Additional information: Error converting data type varchar to bigint. in C#
This Is My Codding i have face this type of error in my code这是我的编码我在我的代码中遇到了这种类型的错误
(Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
(抛出异常:System.Data.dll 中的“System.Data.SqlClient.SqlException”
Additional information: Error converting data type varchar to bigint附加信息:将数据类型 varchar 转换为 bigint 时出错
Update Query:___________________________________更新查询:___________________________________
private void btnUpdate_Click(object sender, EventArgs e)
{
query = ("update items set name='" + txtName.Text + "',category='" + txtCategory.Text + "',price='" + txtPrice.Text + "where iid =" + id + "'");
fn.setData(query);
loadData();
txtName.Clear();
txtCategory.Clear();
txtPrice.Clear();
}
Set Query_______________设置查询_______________
public void setData(String query)
{
SqlConnection con = getConnection();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = query;
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Processed Successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Always try to use Parameterized Query or Stored Procedure , rather than injecting values.始终尝试使用参数化查询或存储过程,而不是注入值。
btnUpdate_Click
private void btnUpdate_Click(object sender, EventArgs e)
{
query = ("update items set name = @name, category = @category, price = @price where iid = @id");
fn.setData(query,long.Parse(id),txtName.Text, txtCategory.Text, long.Parse(txtPrice.Text));
loadData();
txtName.Clear();
txtCategory.Clear();
txtPrice.Clear();
}
setData function
public void setData(String query, long id,string name, string category, long price)
{
SqlConnection con = getConnection();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@category", category);
cmd.Parameters.AddWithValue("@price", price);
cmd.Parameters.Add(new SqlParameter()
{
DbType = System.Data.DbType.Int64, //For big int
Direction = System.Data.ParameterDirection.Input,
ParameterName = "@id",
Value = id
});
try
{
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Processed Successfully.", "Success",MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch(Exception ex)
{
// catch exception here
}
}
Change your code as highlighted below, it should solve your problem.如下所示更改您的代码,它应该可以解决您的问题。
{ {
query = ("update items set name='" + txtName.Text + "',category='" + txtCategory.Text + "',price= " +int.Parse(txtPrice.Text) + "where iid =" + id + "'"); query = ("更新项目集名称='" + txtName.Text + "',category='" + txtCategory.Text + "',price= " +int.Parse(txtPrice.Text) + "where iid=" + id + "'");
fn.setData(query);
loadData();
txtName.Clear();
txtCategory.Clear();
txtPrice.Clear();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.