快速批量导入方法 SqlBulkCopy
1 public string InsertSqlBulkCopy(DataTable dt, string tableName, ref string errinfo) 2 { 3 if (dt.Rows.Count < 1) 4 { 5 return ""; 6 } 7 using (SqlConnection conn = new SqlConnection(SqlHelper.connectionString)) 8 { 9 conn.Open(); 10 SqlTransaction sqlTran = conn.BeginTransaction(); // 开始事务 11 //开始事务 12 using (SqlBulkCopy bcp = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, sqlTran)) 13 { 14 string sql = @" 15 select sourceColumn, destinationColumn from Importsolution where tableName='" + tableName + @"'"; 16 DataTable Importsolution = SqlHelper.GetDataSet(sql).Tables[0]; 17 foreach (DataRow dr in Importsolution.Rows) 18 { 19 bcp.ColumnMappings.Add(dr["sourceColumn"].ToString(), dr["destinationColumn"].ToString()); 20 } 21 22 //指定目标数据库的表名 23 bcp.DestinationTableName = tableName; 24 25 try 26 { 27 //bcp.BulkCopyTimeout = 180; 28 //写入数据库表?dt?是数据源DataTable 29 bcp.WriteToServer(dt); 30 sqlTran.Commit(); 31 32 } 33 catch (Exception ex) 34 { 35 errinfo += ex.Message + ""; 36 sqlTran.Rollback(); 37 } 38 finally 39 { 40 sqlTran.Dispose(); 41 } 42 43 } 44 } 45 return ""; 46 }