2016-08-30 14 views
0

これは基本的にレコードをテーブルに挿入する方法です。 Customer IDがすでにデータベースに存在するかどうかを確認する方法を追加する前に、うまくいきました。プロシージャまたは関数InsertCustomerは、指定された非常に多くの引数があります:私はデータベースに挿入するとSqlExceptionエラーが発生する

「System.Data.SqlClient.SqlException」ののSystem.Data.dllで発生したが、ユーザーコードで

追加情報を扱っていなかった取得します。ライン

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();を使用することができます。しかし、私はこのような問題を避けるために、2つの手順とInsertCustomerの2つの異なる手順を使用することをお勧めします。

サイドノート:データベースに値を試してみましょう。 int.TryParseを使用してください。

+0

データベースがそれをキャストしようとしたくない理由は何ですか?申し訳ありませんが、その愚かなquesiton場合。私はまだ初心者のプログラマーです。 – Anon

+0

@Anon:少なくともAddWithValueでは、データベースは間違った計画につながる可能性のあるパラメータの型を推測しなければなりません。しかし、指定された文字列がC#で有効な整数であるかどうかを確認する方が安全です。クエリを実行せずにエラーメッセージをすぐに表示することができます。 –

0

すでにコマンドにパラメータを追加し、あなたの文からパラメータ以下を削除します。

command.Parameters.Add("@CustID", SqlDbType.Int).Value = txtCID.Text; 
関連する問題