sqlbulkcopy 多表批量保存

/// <summary>
/// 批量保存多表
/// </summary>
/// <param name="dt1"></param>
/// <param name="TableName"></param>
/// <returns></returns>
public static void SqlBatchCopy(DataTable dt, string TableName,DataTable dt1, string TableName1)
{
using (SqlTransaction st = Con.BeginTransaction())
{
using (SqlBulkCopy copy = new SqlBulkCopy(Con, SqlBulkCopyOptions.Default, st))
{
for (int i = 0; i < dt.Columns.Count; i++)
{
copy.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName);
}
copy.DestinationTableName = TableName;
copy.WriteToServer(dt);
}
using (SqlBulkCopy copy = new SqlBulkCopy(Con, SqlBulkCopyOptions.Default, st))
{
for (int i = 0; i < dt1.Columns.Count; i++)
{
copy.ColumnMappings.Add(dt1.Columns[i].ColumnName, dt1.Columns[i].ColumnName);
}
copy.DestinationTableName = TableName1;
copy.WriteToServer(dt1);
}
st.Commit();
}
}

//简单测试

DataTable tb = new DataTable();
tb.Columns.Add( "Cname1", typeof (string));
DataRow dr = tb.NewRow();
for (int i = 1; i <= 10000; i++)
{
dr = tb.NewRow();
dr[ "Cname1"] = "测试" + i;
tb.Rows.Add(dr);
}

System.Diagnostics. Stopwatch st = new System.Diagnostics.Stopwatch();
st.Start();
using (System.Data.SqlClient.SqlBulkCopy copy = new System.Data.SqlClient.SqlBulkCopy ("server=.;database=TestA;uid=sa;pwd=sasa"))
{
copy.ColumnMappings.Add( "Cname1", "Cname" );
copy.DestinationTableName = "TbA";
copy.WriteToServer(tb);
}
st.Stop();
MessageBox.Show( "新增成功,耗时" + st.ElapsedMilliseconds);

 

 

 

 

 

 

 

 

 

 

 

 

  1. class Program  
  2.    {  
  3.        static volatile bool result;  
  4.        static void Main(string[] args)  
  5.        {  
  6.           DataSet ds = ExportDataSet();  
  7.   
  8.           //使用2个线程模拟并发操作  
  9.           Thread t = new Thread(delegate() { result = Insert(ds); Console.WriteLine(result ? "导入成功" : "导入失败"); });  
  10.           t.Start();  
  11.           Thread t1 = new Thread(delegate() { result = Insert(ds); Console.WriteLine(result ? "导入成功" : "导入失败"); });  
  12.           t1.Start();  
  13.           Console.ReadLine();  
  14.        }  
  15.   
  16.        /// <summary>  
  17.        /// 获取数据DataSet  
  18.        /// </summary>  
  19.        /// <returns></returns>  
  20.   
  21.        static private DataSet ExportDataSet()  
  22.        {  
  23.   
  24.            //局域网的某服务器模拟数据库远程连接  
  25.            SqlConnection RemoteConn = new SqlConnection("Data Source=192.168.0.183;Initial Catalog=Northwind;User ID=sa;Password=sa");  
  26.   
  27.   
  28.   
  29.            using (  
  30.   
  31.             /* 目标表与源表结构并不相同,目标表只包含OrderID、CustomerID、EmployeeID、ShipCountry这四个字段。注意这里字段 是区分大小写的,不然SqlBulkCopy的WriteToServer方法会报运行时异常:“给定的 ColumnMapping 与源或目标中的任 意列均不匹配”的处理方法。这个地方浪费了我1个小时才发现*/  
  32.             SqlDataAdapter oda = new SqlDataAdapter("SELECT [OrderID], [CustomerID], [EmployeeID], [ShipCountry] FROM [Northwind].[dbo].[Orders]", RemoteConn))  
  33.   
  34.            //如果目标表与源表结构完全一致,则用下面语句即可,msdn的例子也只是这样  
  35.   
  36.             //SqlDataAdapter oda = new SqlDataAdapter("SELECT * FROM [Ednoland].[dbo].[Score]", RemoteConn))  
  37.            {  
  38.                DataSet ds = new DataSet();  
  39.   
  40.                oda.Fill(ds, "Orders");//给定表名  
  41.   
  42.                  return ds;  
  43.   
  44.            }  
  45.   
  46.        }  
  47.   
  48.        /// <summary>  
  49.        /// 将DataSet导入远程数据库(未来放在WebService中)  
  50.        /// </summary>  
  51.        /// <param name="ds"></param>  
  52.        /// <returns></returns>  
  53.        public static bool Insert(DataSet ds)  
  54.        {  
  55.   
  56.   
  57.            using (SqlConnection sqlconn = new SqlConnection("Data Source=.;Initial Catalog=Northwind;User ID=sa;Password=sa"))  
  58.            {  
  59.                sqlconn.Open();  
  60.                SqlTransaction sqlbulkTransaction = sqlconn.BeginTransaction(IsolationLevel.ReadCommitted);  
  61.   
  62.   
  63.   
  64.                using (SqlBulkCopy sbc = new SqlBulkCopy(sqlconn, SqlBulkCopyOptions.KeepIdentity, sqlbulkTransaction))  
  65.                {  
  66.                    sbc.BatchSize = 20000;//20000行每连接  
  67.                    sbc.BulkCopyTimeout = 50;//50秒超时  
  68.                    if (ds.Tables == null || ds.Tables.Count == 0)  
  69.                        return false;  
  70.   
  71.                    if (ds.Tables.Count == 1)  
  72.                    {  
  73.   
  74.   
  75.                        return BulkInsert(sbc, ds.Tables[0], sqlbulkTransaction); ;  
  76.   
  77.                    }  
  78.                    else  
  79.                    {  
  80.                        bool res = true;  
  81.                        foreach (DataTable dt in ds.Tables)  
  82.                        {  
  83.   
  84.                            res = BulkInsert(sbc, dt, sqlbulkTransaction);  
  85.   
  86.                        }  
  87.                        return res;  
  88.                    }  
  89.   
  90.                }  
  91.            }  
  92.   
  93.        }  
  94.   
  95.        private static bool BulkInsert(SqlBulkCopy sbc, DataTable dt, SqlTransaction sqlbulkTransaction)  
  96.        {  
  97.           
  98.            bool res = true;  
  99.                       try  
  100.            {  
  101.   
  102.              //将DataTable表名作为待导入库中的目标表名  
  103.                sbc.DestinationTableName = dt.TableName;  
  104.   
  105.   
  106.   
  107.               //将数据集合和目标服务器库表中的字段对应  
  108.                for (int i = 0; i < dt.Columns.Count; i++)  
  109.                {  
  110.                    //sbc.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName);  
  111.                      sbc.ColumnMappings.Add(i,i);//可以避免字段大小写不一致造成无法映射的问题  
  112.                }  
  113.   
  114.                sbc.WriteToServer(dt);  
  115.   
  116.                //提交事务  
  117.                sqlbulkTransaction.Commit();  
  118.                res = true;  
  119.            }  
  120.            catch (SqlException ex)  
  121.            {  
  122.                res = false;  
  123.                sqlbulkTransaction.Rollback();  
  124.            }  
  125.   
  126.            return res;  
  127.        }  
  128.    }  
posted @ 2019-01-15 21:54  星火卓越  阅读(549)  评论(0编辑  收藏  举报