2016-08-30 46 views
0

这基本上是一种将记录插入表的方法。在我决定添加一种方法来检查客户ID是否已经存在于数据库中之前,它工作正常。我得到一个当我插入数据库时​​发生SqlException错误

“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(); 
} 

回答

3

您两次添加相同的参数:

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

您可以使用command.Parameters.Clear();。但我更愿意使用两种不同的SqlCommands来执行两个程序CheckDetailsInsertCustomer以避免此类问题。

附注:不要让数据库尝试为您输入值。使用int.TryParse

+0

什么是你不想要的数据库尝试投它的原因是什么?对不起,如果它是一个愚蠢的quesiton。我仍然是一名初学者程序员。 – Anon

+0

@Anon:至少使用AddWithValue,数据库必须猜测可能导致计划错误的参数类型。但是,检查给定的字符串是否是C#中的有效整数也更安全。您可以立即显示错误消息而不执行查询。 –

0

以下参数从语句中删除,你已经在命令添加参数:

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