2016-04-18 5 views
-4

C#ツールからSQLクエリを実行して、挿入を試みる際に問題があります。時間の間にテキストボックス(テキストボックスが空の場合)に 'NULL'ワードを割り当てる方法は?

文字列が空の場合(ユーザーが入力していない場合)、NULL値を挿入する必要があります。 DBのNULL値と通常の文字列 'NULL'を使ってNULL挿入を試みましたが、空の値(NULLキーワードのinsetead)が表示され、エラーが表示されます。誰もがこのためのソリューションを持っている場合、私に教えてください

....

以下はあなたがこの種のコードを避ける必要があります私のコード

if (comboBox_ConfacValue.Text == "") 
{ 
    comboBox_ConfacValue.Text = DBNull.Value.ToString(); 
} 

if (combobox_conversionDescription.Text == "") 
{ 
    combobox_conversionDescription.Text = "NULL"; 
} 

try 
{ 
    con.Open(); 

    if (MessageBox.Show("Do you really want to Insert these values?", "Confirm Insert", MessageBoxButtons.YesNo) == DialogResult.Yes) 
    { 
     SqlDataAdapter SDA = new SqlDataAdapter(@" insert INTO Table1 (alpha1,alpha2,alpha3) VALUES ('" + comboBox_ConfacValue.Text + "','" + combobox_conversionDescription.Text + "','"+ combobox_Description.Text + "',')",con) 

     SDA.SelectCommand.ExecuteNonQuery(); 
     MessageBox.Show("Inserted successfully."); 
    } 
} 
+0

がnull値がwitout設定しなければならないと呼ばれています'、null)not(' 1 '、' null ')。あなたのインサートプロダクション( '1'、 'ヌル')。より良いaprouchは接続にパラメータを設定することです –

+0

どのデータベースを使用していますか? – Phoenician

+3

誰かが_ _を入力した場合どうなりますか? DROP TABLE Table1; --_ Sql Injectionについて学び、パラメータを使用する – Steve

答えて

2

です。文字列を連結してsqlコマンドを生成することは、災害のレシピです。エラーの解析は「((...)表1に挿入するインサート内のシンボル値が」1よくある間違いですが、より悪い敵は、このパターンの背後に潜んされ、Sql Injection

try 
    { 
     con.Open(); 
     if (MessageBox.Show("Do you really want to Insert these values?", "Confirm Insert", MessageBoxButtons.YesNo) == DialogResult.Yes) 
     { 
      // Now the command text is no more built from pieces of 
      // of user input and it is a lot more clear 
      SqlCommand cmd = new SqlCommand(@"insert INTO Table1 
       (alpha1,alpha2,alpha3) 
       VALUES (@a1, @a2, @a3)", con); 
      // For every parameter placeholder add the respective parameter 
      // and set the DbNull.Value when you need it 
      cmd.Parameters.Add("@a1", SqlDbType.NVarChar).Value = 
       string.IsNullOrEmpty(comboBox_ConfacValue.Text) ? 
           DbNull.Value : comboBox_ConfacValue.Text); 

      cmd.Parameters.Add("@a2", SqlDbType.NVarChar).Value = 
       string.IsNullOrEmpty(combobox_conversionDescription.Text) ? 
           DbNull.Value : combobox_conversionDescription.Text); 

      cmd.Parameters.Add("@a3", SqlDbType.NVarChar).Value = 
       string.IsNullOrEmpty(combobox_Description.Text) ? 
           DbNull.Value : combobox_Description.Text); 

      // Run the command, no need to use all the infrastructure of 
      // an SqlDataAdapter here.... 
      int rows = cmd.ExecuteNonQuery(); 

      // Check the number of rows added before message... 
      if(rows > 0) MessageBox.Show("Inserted Successfully."); 
+0

パラメータ値にサブクエリを使用する必要がある場合はどうすればよいですか? –

+0

(サーバー上の)Sql Parserの観点からは、パラメーターのプレースホルダーの位置には違いはありません。 – Steve

+0

クール私はそれを試してみる..ありがとう –

関連する問題