批量插入数据库
1 /// <summary> 2 /// 批量插入数据库 3 /// </summary> 4 /// <param name="TableName">目标表</param> 5 /// <param name="dt">源数据</param> 6 public bool SqlBulkCopyByDatatable(string TableName, DataTable dt) 7 { 8 using (SqlConnection conn = new SqlConnection(connectionString)) 9 { 10 using (SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction)) 11 { 12 try 13 { 14 sqlbulkcopy.DestinationTableName = TableName; 15 for (int i = 0; i < dt.Columns.Count; i++) 16 { 17 sqlbulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName); 18 } 19 sqlbulkcopy.WriteToServer(dt); 20 return true; 21 } 22 catch (System.Exception ex) 23 { 24 //ex.Message; 25 return false; 26 } 27 } 28 } 29 }
List<T> 、 model 相互转换
1 /// <summary> 2 /// 批量插入数据库 3 /// </summary> 4 /// <param name="TableName">目标表</param> 5 /// <param name="dt">源数据</param> 6 public bool SqlBulkCopyByDatatable(string TableName, DataTable dt) 7 { 8 using (SqlConnection conn = new SqlConnection(connectionString)) 9 { 10 using (SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction)) 11 { 12 try 13 { 14 sqlbulkcopy.DestinationTableName = TableName; 15 for (int i = 0; i < dt.Columns.Count; i++) 16 { 17 sqlbulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName); 18 } 19 sqlbulkcopy.WriteToServer(dt); 20 return true; 21 } 22 catch (System.Exception ex) 23 { 24 //ex.Message; 25 return false; 26 } 27 } 28 } 29 }