且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Storedprocedure更新数据库内的值

更新时间:2023-02-07 11:37:52

错误信息非常清楚:



The error message is pretty clear:

Quote:

转换时转换失败varchar值'@EmpId'到数据类型int。

Conversion failed when converting the varchar value '@EmpId' to data type int.





您传入的EmpId值不是int。您应该做的是验证客户端和服务器端的输入。



AddWithValue会将参数发送为nvarchar并尝试执行隐式转换与并不总是一件好事。你应该使用下面的东西。





You are passing in a value for EmpId that is not an int. What you should be doing is validating the input in the client side as well as the server side.

AddWithValue will send you parameter as nvarchar and try to preform an implicit conversion with is not always a great thing. You should use something like below.

cmd.Parameters.Add("@EmpId", SqlDbType.Int);
cmd.Parameters["@EmpId"].Value = txtEmpId.Text;


在传递给存储过程之前将 @EmpId 转换为int

Convert your @EmpId to int before passing to stored procedure
Convert.ToInt32(txtEmpId.Text);


对于参数很少的程序,我使用它,从而确保所有类型的数据都能正常工作,如果你有布尔数据,整数或日期工作。

For procedures with few parameters I use this, thus ensures that all types of data work, if you have Boolean data, integer or datetime work.
protected void btnUpdate_Click(object sender, EventArgs e)
{
bool t = sp_update(txtEmpId.Text,txtEmployeeName.Text,txtEmpAddress.Text,txtMobile.Text);
if (t)
{
lblResult.Text = "Value Updated";
}
else
{
lblResult.Text = "Failed";
} 
}

public bool sp_update( string EmpId ,string EmpName,string EmpAdd,string Phone)
{
	bool _flag = false;
    SqlConnection _conn = new SqlConnection(connstr);
	try
	{
		SqlCommand _cmd = new SqlCommand();
		_cmd.Connection = _conn;
		_cmd.CommandType = CommandType.Text;
		_cmd.CommandText = String.Format(" exec dbo.sp_Update @EmpId ='{0}',@EmpName='{1}',@EmpAdd='{2}',@Phone='{3}'", EmpId ,EmpName,EmpAdd,Phone);
		_conn.Open();
		_cmd.ExecuteNonQuery();
		_conn.Close();
		_flag = true;
	}
	catch (ServiciosSqlNet.SqlNetException ex)
	{
		throw new Exception(ex.Message, (Exception)ex);
	}
	catch (Exception ex)
	{
		throw ex;
	}
	return _flag;
}