c#批量插入数据 C# SqlBulkCopy使用

  1. private static void DataTableToSQLServer( DataTable dt)  

  2. {  

  3.     string connectionString = GetConnectionString();  

  4.   

  5.     using (SqlConnection destinationConnection =new SqlConnection(connectionString))  

  6.     {  

  7.         destinationConnection.Open();  

  8.   

  9.         using (SqlBulkCopy bulkCopy =new SqlBulkCopy(destinationConnection))  

  10.         {  

  11.   

  12.   

  13.             try  

  14.             {  

  15.   

  16.                 bulkCopy.DestinationTableName = "T_EIInformation";//要插入的表的表明  

  17.                 bulkCopy.ColumnMappings.Add("Email""Email");//映射字段名 DataTable列名 ,数据库 对应的列名  

  18.                 bulkCopy.ColumnMappings.Add("author""author");  

  19.                 bulkCopy.ColumnMappings.Add("Title""Title");  

  20.                 bulkCopy.ColumnMappings.Add("Type""Type");  

  21.                 bulkCopy.ColumnMappings.Add("confName""confName");  

  22.                 bulkCopy.ColumnMappings.Add("Language""Language");  

  23.                 bulkCopy.ColumnMappings.Add("Publicationyear""Publicationyear");  

  24.                 bulkCopy.ColumnMappings.Add("Conferencelocation""Conferencelocation");  

  25.                 bulkCopy.WriteToServer(dt);  

  26.             }  

  27.             catch (Exception ex)  

  28.             {  

  29.                 Console.WriteLine(ex.Message);  

  30.             }  

  31.             finally  

  32.             {  

  33.                 // Close the SqlDataReader. The SqlBulkCopy  

  34.                 // object is automatically closed at the end  

  35.                 // of the using block.  

  36.                  

  37.             }  

  38.         }  

  39.   

  40.   

  41.     }  

  42.       

  43. }  


你可能感兴趣的:(批量插入数据)