插入数据库

时间:2016-08-30 08:35:36

标签: c# sql sql-server

这基本上是一种将记录插入表中的方法。在我决定添加一种方法来检查数据库中是否已存在客户ID之前,它工作正常。我得到了

  

'System.Data.SqlClient.SqlException'在System.Data.dll中发生但未在用户代码中处理

     

其他信息:过程或函数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();
}

2 个答案:

答案 0 :(得分:3)

您要添加两次相同的参数:

command.Parameters.AddWithValue("@CustID", txtCID.Text);
// ....
command.Parameters.Add("@CustID", SqlDbType.Int).Value = txtCID.Text;

您可以使用command.Parameters.Clear();。但我希望对两个程序SqlCommandsCheckDetails使用两个不同的InsertCustomer来避免此类问题。

旁注:不要让数据库为您试用值。使用int.TryParse

答案 1 :(得分:0)

从语句中删除下面的参数,您已在命令中添加参数:

command.Parameters.Add("@CustID", SqlDbType.Int).Value = txtCID.Text;