2016-03-29 9 views
1

C#Windowsアプリケーションのgridviewを使用してデータベースに値を挿入しようとしています。私は2つの異なる方法を試みたが、どちらも私のために働いているようだ。 2つのタイプのコードは以下に示されています......グリッドビューからデータを挿入するときの 'NULL'とキー制約の処理

以下のコードが動作しても、私は主キーと外部キーの制約に関してさまざまなエラーが発生しています...... 。

問題:

  1. 私が先businesslogicテーブル内のNULL可能で整数としてconfactorIDmacroID列を持っている.......私はからこれらの列に「NULL」を挿入するかどうかはわかりませんC#gridviewツール...

  2. ....

が、私はこれらの問題を解決するために、私の次のコードに変更すること何が必要なのか、私は、入力として整数値を与えた場合でも、外部キーと主キー(重複)制約の問題があるようです。.. ..私は8時間以上これらの問題に立ち往生してきました...どんな助けも大歓迎です。

コードタイプ1:

private void ADD_button_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      using (SqlConnection con = new SqlConnection(sqlconn)) 
      { 
       using (SqlCommand cmd = new SqlCommand()) 
       { 
        cmd.Connection = con; 
        con.Open(); 

        for (int i = 1; i < dataGridView.Rows.Count; i++) 
        { 
         string sql = @"INSERT INTO " + schemaName +"ERSBusinessLogic VALUES (" 
             + dataGridView.Rows[i].Cells["ERSBusinessLogic_ID"].Value + ", '" 
             + dataGridView.Rows[i].Cells["ERSBusinessLogic_Formula"].Value.ToString() + "', " 
             + dataGridView.Rows[i].Cells["ERSBusinessLogic_InputsCount"].Value + ",'" 
             + dataGridView.Rows[i].Cells["ERSBusinessLogic_Inputs"].Value.ToString() + "', " 
             + dataGridView.Rows[i].Cells["ERSBusinessLogic_ConvFactorID"].Value + ", " 
             + dataGridView.Rows[i].Cells["ERSBusinessLogic_MacroID"].Value + ", '" 
             + dataGridView.Rows[i].Cells["ERSBusinessLogic_DataSeries"].Value.ToString() + "', '" 
             + dataGridView.Rows[i].Cells["ERSBusinessLogic_InputTimeDimensionValue"].Value.ToString() + "', " 
             + dataGridView.Rows[i].Cells["ERSBusinessLogic_InputTimeDimensionType"].Value + ", " 
             + dataGridView.Rows[i].Cells["ERSBusinessLogic_GeographyDimensionID"].Value + ", " 
             + dataGridView.Rows[i].Cells["ERSBusinessLogic_InputsUnitsIDs"].Value + ", '" 
             + dataGridView.Rows[i].Cells["ERSBusinessLogic_Type"].Value + "', " 
             + dataGridView.Rows[i].Cells["ERSBusinessLogic_PrivacyID"].Value + ", '" 
             + dataGridView.Rows[i].Cells["ERSBusinessLogic_LongDesc"].Value.ToString() + "', '" 
             + dataGridView.Rows[i].Cells["ERSBusinessLogic_InputSources"].Value.ToString() + "', '" 
             + dataGridView.Rows[i].Cells["ERSBusinessLogic_OutputName"].Value.ToString() + "', " 
             + dataGridView.Rows[i].Cells["ERSBusinessLogic_OutputUnitID"].Value + ", '" 
             + dataGridView.Rows[i].Cells["ERSBusinessLogic_OutputDestination"].Value.ToString() + "', '" 
             + dataGridView.Rows[i].Cells["ERSBusinessLogic_OutputTimeDimensionValue"].Value.ToString() + "', " 
             + dataGridView.Rows[i].Cells["ERSBusinessLogic_OutputTimeDimensionType"].Value + ", " 
             + dataGridView.Rows[i].Cells["ERSBusinessLogic_GroupID"].Value + ");"; 

         if ((dataGridView.Rows[i].Cells["ERSBusinessLogic_ConvFactorID"].Value == " ") && (dataGridView.Rows[i].Cells["ERSBusinessLogic_MacroID"].Value == null)) 
         { 
          Convert.ToInt32(dataGridView.Rows[i].Cells["ERSBusinessLogic_ConvFactorID"].Value = "NULL"); 
          Convert.ToInt32 (dataGridView.Rows[i].Cells["ERSBusinessLogic_MacroID"].Value = "NULL"); 

          cmd.CommandText = sql; 
          cmd.ExecuteNonQuery(); 
         } 
         else 
         { 
          cmd.CommandText = sql; 
          cmd.ExecuteNonQuery(); 
         } 
        } 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show("Error : " + ex.Message); 
     } 
     finally 
     { 
      con.Close(); 
     } 
    } 

コードタイプ2:

private void ADD_button_Click(object sender, EventArgs e) 
{ 
    // Getting data from DataGridView 
    DataTable myDt = new DataTable(); 
    myDt = GetDTfromDGV(dataGridView); 

    // Writing to sql 
    WriteToSQL(myDt); 
} 

private DataTable GetDTfromDGV(DataGridView dgv) 
{ 
    // Making our DataTable 
    DataTable dt = new DataTable(); 

    foreach (DataGridViewColumn column in dgv.Columns) 
    { 
     dt.Columns.Add(column.Name, typeof(string)); 
    } 

    // Getting data 
    foreach (DataGridViewRow dgvRow in dgv.Rows) 
    { 
     DataRow dr = dt.NewRow(); 

     for (int col = 0; col < dgv.Columns.Count; col++) 
     { 
      dr[col] = dgvRow.Cells[col].Value; 
     } 

     dt.Rows.Add(dr); 
    } 

    // removing empty rows 
    for (int row = dt.Rows.Count - 1; row >= 0; row--) 
    { 
     bool flag = true; 

     for (int col = 0; col < dt.Columns.Count; col++) 
     { 
      if (dt.Rows[row][col] != DBNull.Value) 
      { 
       flag = false; 
       break; 
      } 
     } 

     if (flag == true) 
     { 
      dt.Rows.RemoveAt(row); 
     } 
    } 

    return dt; 
} 

private void WriteToSQL(DataTable dt) 
{ 
    using (SqlConnection con = new SqlConnection(sqlconn)) 
    { 
     SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con); 
     // Setting the database table name 
     sqlBulkCopy.DestinationTableName = "[AnimalProductsCoSD].[CoSD].[ERSBusinessLogic]"; 
     // Mapping the DataTable columns with that of the database table 
     Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[0].ColumnName, "ERSBusinessLogic_ID")); 
     Convert.ToString(sqlBulkCopy.ColumnMappings.Add(dt.Columns[1].ColumnName, "ERSBusinessLogic_Formula")); 
     Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[2].ColumnName, "ERSBusinessLogic_InputsCount")); 
     Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[3].ColumnName, "ERSBusinessLogic_Inputs")); 
     Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[4].ColumnName, "ERSBusinessLogic_ConvFactorID")); 
     Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[5].ColumnName, "ERSBusinessLogic_MacroID")); 

     Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[6].ColumnName, "ERSBusinessLogic_DataSeries")); 
     Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[7].ColumnName, "ERSBusinessLogic_InputTimeDimensionValue")); 
     Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[8].ColumnName, "ERSBusinessLogic_InputTimeDimensionType")); 
     Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[9].ColumnName, "ERSBusinessLogic_GeographyDimensionID")); 
     Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[10].ColumnName, "ERSBusinessLogic_InputsUnitsIDs")); 
     Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[11].ColumnName, "ERSBusinessLogic_Type")); 

     Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[12].ColumnName, "ERSBusinessLogic_PrivacyID")); 
     Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[13].ColumnName, "ERSBusinessLogic_LongDesc")); 
     Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[14].ColumnName, "ERSBusinessLogic_InputSources")); 
     Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[15].ColumnName, "ERSBusinessLogic_OutputName")); 
     Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[16].ColumnName, "ERSBusinessLogic_OutputUnitID")); 
     Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[17].ColumnName, "ERSBusinessLogic_OutputDestination")); 

     Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[18].ColumnName, "ERSBusinessLogic_OutputTimeDimensionValue")); 
     Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[19].ColumnName, "ERSBusinessLogic_OutputTimeDimensionType")); 
     Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[20].ColumnName, "ERSBusinessLogic_GroupID")); 

     con.Open(); 
     sqlBulkCopy.WriteToServer(dt); 
    } 
} 

おかげ

答えて

3

まず第一には、データベースのテーブルをチェックし、別のテーブルからIDを保持カラムはそうのようにnull値を許可する必要があります。 enter image description here

そして、あなたのテーブルIDが自動インクリメントとID列である場合、あなたはしないでくださいIDを書く必要があり、テーブルは自動的にIDを追加します。 [OK]を、すべてがそうのように実行しようとした場合

は:

private DataTable GetDTfromDGV(DataGridView dgv) 
    { 
     // Macking our DataTable 
     DataTable dt = new DataTable(); 
     //Another way to add columns 
     dt.Columns.AddRange(new DataColumn[5] 
      { 
       //new DataColumn("table_ID", typeof(string)), if table_ID is not Identity column with auto increment then uncomment 
       new DataColumn("sql_col2", typeof(string)), 
       new DataColumn("sql_col3", typeof(string)), 
       new DataColumn("sql_col4", typeof(string)), 
       new DataColumn("Table_2_ID", typeof(int)), 
       new DataColumn("Table_3_IDt", typeof(int)) 
      }); 
     // Getting data 
     foreach (DataGridViewRow dgvRow in dgv.Rows) 
     { 
      DataRow dr = dt.NewRow(); 
      for (int col = 1; col < dgv.Columns.Count; col++) //if table_ID is not Identity column with auto increment then start with 0 
      { 
       dr[col - 1] = dgvRow.Cells[col].Value == null ? DBNull.Value : dgvRow.Cells[col].Value; 
      } 
      dt.Rows.Add(dr); 
     } 
     // removing empty rows 
     .... 
     return dt; 
    } 
    private void WriteToSQL(DataTable dt) 
    { 
     string connectionStringSQL = "Your connection string"; 
     using (SqlConnection sqlConn = new SqlConnection(connectionStringSQL)) 
     { 
      SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sqlConn); 
      // Setting the database table name 
      sqlBulkCopy.DestinationTableName = "Table_1"; 
      // Mapping the DataTable columns with that of the database table 
      //sqlBulkCopy.ColumnMappings.Add(dt.Columns[0].ColumnName, "table_ID"); table_ID is Identity column with auto increment 
      sqlBulkCopy.ColumnMappings.Add(dt.Columns[0].ColumnName, "sql_col2"); 
      sqlBulkCopy.ColumnMappings.Add(dt.Columns[1].ColumnName, "sql_col3"); 
      sqlBulkCopy.ColumnMappings.Add(dt.Columns[2].ColumnName, "sql_col4"); 
      sqlBulkCopy.ColumnMappings.Add(dt.Columns[3].ColumnName, "Table_2_ID"); 
      sqlBulkCopy.ColumnMappings.Add(dt.Columns[4].ColumnName, "Table_3_ID"); 
      sqlConn.Open(); 
      sqlBulkCopy.WriteToServer(dt); 
     } 
    } 

は、私が試した、それは私が得たものです: enter image description here

enter image description here

0

あなたはパラメータ化クエリを使用することができます。たとえば :

  var sqlcommand = new SqlCommand 
      { 
       CommandText = "INSERT INTO TABLE(Column1,Column2) VALUES(@Column1Value,@Column2Value)" 
      }; 
      var param1 = new SqlParameter("@Column1Value", SqlDbType.Int) 
      { 
       Value = (String.IsNullOrWhiteSpace(dataGridView.Rows[i].Cells["ERSBusinessLogic_ConvFactorID"].Value)) ? DBNull.Value: (object)(dataGridView.Rows[i].Cells["ERSBusinessLogic_ConvFactorID"].Value) 
      }; 
      var param2 = new SqlParameter("@Column2Value", SqlDbType.Int) 
      { 
       Value = (String.IsNullOrWhiteSpace(dataGridView.Rows[i].Cells["ERSBusinessLogic_MacroID"].Value)) ? DBNull.Value : (object)dataGridView.Rows[i].Cells["ERSBusinessLogic_MacroID"].Value) 
      }; 
      sqlcommand.Parameters.Add(param1); 
      sqlcommand.Parameters.Add(param2); 
0

あなたがしようとした方法1を使用する場合、あなたはおそらくSqlParameterオブジェクトを作成し、クエリをパラメータ化したいと思います。これを参照してください投稿:Right syntax of SqlParameter。それは言われている、あなたはただそれを最初に私は確信している得るようにしたい。 convFactorIDとmacroIDのDataGridViewCellのValueプロパティの値を確認できます。これらのいずれかがNULLの場合は、文字列に "NULL"という文字列を割り当てることができます。簡潔にするために、私はC#の条件演算子(https://msdn.microsoft.com/en-us/library/ty67wk28.aspx)を使用しました。

string convFactorIDText = (dataGridView.Rows[i].Cells["ERSBusinessLogic_ConvFactorID"].Value == null) ? "NULL" : dataGridView.Rows[i].Cells["ERSBusinessLogic_ConvFactorID"].Value.ToString(); 
string macroIDText = (dataGridView.Rows[i].Cells["ERSBusinessLogic_MacroID"].Value == null) ? "NULL" : dataGridView.Rows[i].Cells["ERSBusinessLogic_MacroID"].Value.ToString(); 

を次に実際の値またはNULLのいずれかを含む文字列変数を含めるようにあなたのSQLを変更する:これは、私が説明してる何を行う可能性があります1つの方法です。

string sql = string.Format(@"INSERT INTO {0}.ERSBusinessLogic VALUES ({1}, '{2}', {3}, {4}, {5}, {6}"), 
    schemaName, 
    dataGridView.Rows[i].Cells["ERSBusinessLogic_ID"].Value, 
    dataGridView.Rows[i].Cells["ERSBusinessLogic_Formula"].Value.ToString(), 
    dataGridView.Rows[i].Cells["ERSBusinessLogic_InputsCount"].Value, 
    dataGridView.Rows[i].Cells["ERSBusinessLogic_Inputs"].Value, 
    convFactorIDText, 
    macroIDText 
    // and so forth 
); 
関連する問題