2016-03-08 36 views
0

餵我有這個狙擊這樣的代碼:插入SQL經由sqlbulk

public static void Put_CSVtoSQL_Adhesion() 
    { 
     bool IsFirst = true;  
     DataTable dt = new DataTable(); 
     string line = null; 
     int i = 0; 

     try 
     { 
      string fileName = Path.Combine(HttpContext.Current.Server.MapPath(UploadDirectory), TheFileName); 

      using (StreamReader sr = File.OpenText(fileName)) 
      { 
       while ((line = sr.ReadLine()) != null) 
       { 
        string[] data = line.Split(';'); 
        if (data.Length > 0) 
        { 
         if (i == 0) 
         { 
          foreach (var item in data) 
          { 
           dt.Columns.Add(new DataColumn()); 
          } 
          i++; 
         } 
         DataRow row = dt.NewRow(); 
         row.ItemArray = data; 

         // Pour enlever la tete 
         if (!IsFirst) dt.Rows.Add(row); 
         IsFirst = false; 
        } 
       } 
      } 

      using (var connectionWrapper = new Connexion()) 
      { 
       var connectedConnection = connectionWrapper.GetConnected(); 
       using (SqlBulkCopy copy = new SqlBulkCopy(connectionWrapper.conn)) 
       { 
        int CountColl = dt.Columns.Count; 

        copy.ColumnMappings.Add(0, 1); 
        copy.ColumnMappings.Add(1, 2); 
        copy.ColumnMappings.Add(2, 3); 
        copy.ColumnMappings.Add(3, 4); 
        copy.ColumnMappings.Add(4, 5); 


        copy.DestinationTableName = "cotisation"; 
        copy.WriteToServer(dt); 
       } 
      } 
     } 
     catch (Exception excThrown) 
     { 
      throw new Exception(excThrown.Message); 
     } 
    } 

此代碼的工作很好,但現在我有超過60柱,我應該manualy鍵入從1至60柱或有另一種方法?

copy.ColumnMappings.Add(0, 1); 
        copy.ColumnMappings.Add(1, 2); 
        copy.ColumnMappings.Add(2, 3); 
        copy.ColumnMappings.Add(3, 4); 
        copy.ColumnMappings.Add(4, 5); 

...直到60列?

列是所有的i只是移位1列中,因爲第一個是自動增量列作爲ID

回答

1

同一寫循環?

for (int i = 0; i < dt.Columns.Count - 1; i++) 
{ 
    copy.ColumnMappings.Add(i, i + 1); 
}