SqlBulkCopy批量插入大数据
作者:互联网
1 /// <summary> 2 /// 按照SqlBulkCopy写入数据库 3 /// </summary> 4 /// <param name="dt">数据表</param> 5 /// <param name="tableName">数据库表名</param> 6 public static void WriteDataBySqlBulkCopy(DataTable dt, string tableName, string connStr = null) 7 { 8 //判空 9 if (dt == null || dt.Rows.Count == 0 || string.IsNullOrEmpty(tableName)) 10 { 11 return; 12 } 13 SqlConnection con = new SqlConnection(connStr); 14 if (con.State != ConnectionState.Open) 15 { 16 con.Open(); 17 } 18 //此部分是重要的东西 19 using (System.Data.SqlClient.SqlBulkCopy sbc = new System.Data.SqlClient.SqlBulkCopy(con)) 20 { 21 22 try 23 { 24 for (int i = 0; i < dt.Columns.Count; i++) 25 { 26 27 sbc.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName); //设置目标表和源数据的列映射 28 } 29 sbc.DestinationTableName = tableName; //取得目标表名 30 sbc.WriteToServer(dt); 31 32 } 33 catch (Exception ex) 34 { 35 Console.WriteLine(ex.Message); 36 } 37 finally 38 { 39 if (con.State == ConnectionState.Open) 40 { 41 con.Close(); 42 } 43 } 44 } 45 }
标签:string,批量,sbc,tableName,SqlBulkCopy,插入,dt,con 来源: https://www.cnblogs.com/wzf-Learning/p/16280114.html