这基本上是一种将记录插入表中的方法。在我决定添加一种方式来检查数据库中是否已经存在客户ID之前,它运行良好。我得到一个
System.Data.dll中发生“ System.Data.SqlClient.SqlException”,但未在用户代码中处理
附加信息:过程或函数InsertCustomer指定的参数过多。
在线上
command.ExecuteNonQuery();
我不明白怎么了
public void add()
{
lblMessage.Text = "";
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "CheckDetails";
command.Parameters.AddWithValue("@CustID", txtCID.Text);
conn.Open();
int check = (int)command.ExecuteScalar();
if (check == 0)
{
command.CommandText = "InsertCustomer";
command.Parameters.Add("@CustID", SqlDbType.Int).Value = txtCID.Text;
command.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFName.Text;
command.Parameters.Add("@Surname", SqlDbType.VarChar).Value = txtLName.Text;
command.Parameters.Add("@Gender", SqlDbType.VarChar).Value = rdoGender.Text;
command.Parameters.Add("@Age", SqlDbType.Int).Value = txtAge.Text;
command.Parameters.Add("@Address1", SqlDbType.VarChar).Value = txtAdd1.Text;
command.Parameters.Add("@Address2", SqlDbType.VarChar).Value = txtAdd2.Text;
command.Parameters.Add("@City", SqlDbType.VarChar).Value = txtCity.Text;
command.Parameters.Add("@Phone", SqlDbType.VarChar).Value = txtPhone.Text;
command.Parameters.Add("@Mobile", SqlDbType.VarChar).Value = txtMobile.Text;
command.Parameters.Add("@Email", SqlDbType.VarChar).Value = txtEmail.Text;
command.ExecuteNonQuery();
lblMessage.Text = "Customer Details Added.";
}
else
{
lblMessage.Text = "Customer ID already exists.";
}
conn.Close();
}
您将两次添加相同的参数:
command.Parameters.AddWithValue("@CustID", txtCID.Text);
// ....
command.Parameters.Add("@CustID", SqlDbType.Int).Value = txtCID.Text;
您可以使用command.Parameters.Clear();
。但是我宁愿对这SqlCommands
两个过程使用两个不同的方法,CheckDetails
并InsertCustomer
避免此类问题。
旁注:不要让数据库为您尝试值。使用int.TryParse
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句