这基本上是一个将记录插入到表中的方法。在我决定添加一种检查客户ID是否已经存在于数据库中的方式之前,它工作得很好。我得到一个
System.Data.SqlClient。在System.Data.dll中发生了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();
。但我更愿意为CheckDetails
和InsertCustomer
两个程序使用两个不同的SqlCommands
,以避免此类问题。
旁注:不要让数据库为您尝试强制转换值。使用int.TryParse
从语句中删除下面的参数,您已经在命令中添加了参数:
command.Parameters.Add("@CustID", SqlDbType.Int).Value = txtCID.Text;