This Is My Codding i have face this type of error in my code (Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
Additional information: Error converting data type varchar to 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);
}
CodePudding user response:
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);
loadData();
txtName.Clear();
txtCategory.Clear();
txtPrice.Clear();
}
setData function
public void setData(String query)
{
SqlConnection con = getConnection();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("@name", txtName.Text);
cmd.Parameters.AddWithValue("@category", txtCategory.Text);
cmd.Parameters.AddWithValue("@price", txtPrice.Text);
cmd.Parameters.Add(new SqlParameter()
{
DbType = System.Data.DbType.Int64, //For big int
Direction = System.Data.ParameterDirection.Input,
ParameterName = "@id",
Value = Convert.ToInt64(id)
});
try
{
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Processed Successfully.", "Success",MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch(Exception ex)
{
// catch exception here
}
}
CodePudding user response:
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 "'");
fn.setData(query);
loadData();
txtName.Clear();
txtCategory.Clear();
txtPrice.Clear();
}