- class Program
- {
- static volatile bool result;
- static void Main(string[] args)
- {
- DataSet ds = ExportDataSet();
-
-
- Thread t = new Thread(delegate() { result = Insert(ds); Console.WriteLine(result ? "导入成功" : "导入失败"); });
- t.Start();
- Thread t1 = new Thread(delegate() { result = Insert(ds); Console.WriteLine(result ? "导入成功" : "导入失败"); });
- t1.Start();
- Console.ReadLine();
- }
-
-
-
-
-
-
- static private DataSet ExportDataSet()
- {
-
-
- SqlConnection RemoteConn = new SqlConnection("Data Source=192.168.0.183;Initial Catalog=Northwind;User ID=sa;Password=sa");
-
-
-
- using (
-
-
- SqlDataAdapter oda = new SqlDataAdapter("SELECT [OrderID], [CustomerID], [EmployeeID], [ShipCountry] FROM [Northwind].[dbo].[Orders]", RemoteConn))
-
-
-
-
- {
- DataSet ds = new DataSet();
-
- oda.Fill(ds, "Orders");
-
- return ds;
-
- }
-
- }
-
-
-
-
-
-
- public static bool Insert(DataSet ds)
- {
-
-
- using (SqlConnection sqlconn = new SqlConnection("Data Source=.;Initial Catalog=Northwind;User ID=sa;Password=sa"))
- {
- sqlconn.Open();
- SqlTransaction sqlbulkTransaction = sqlconn.BeginTransaction(IsolationLevel.ReadCommitted);
-
-
-
- using (SqlBulkCopy sbc = new SqlBulkCopy(sqlconn, SqlBulkCopyOptions.KeepIdentity, sqlbulkTransaction))
- {
- sbc.BatchSize = 20000;
- sbc.BulkCopyTimeout = 50;
- if (ds.Tables == null || ds.Tables.Count == 0)
- return false;
-
- if (ds.Tables.Count == 1)
- {
-
-
- return BulkInsert(sbc, ds.Tables[0], sqlbulkTransaction); ;
-
- }
- else
- {
- bool res = true;
- foreach (DataTable dt in ds.Tables)
- {
-
- res = BulkInsert(sbc, dt, sqlbulkTransaction);
-
- }
- return res;
- }
-
- }
- }
-
- }
-
- private static bool BulkInsert(SqlBulkCopy sbc, DataTable dt, SqlTransaction sqlbulkTransaction)
- {
-
- bool res = true;
- try
- {
-
-
- sbc.DestinationTableName = dt.TableName;
-
-
-
-
- for (int i = 0; i < dt.Columns.Count; i++)
- {
-
- sbc.ColumnMappings.Add(i,i);
- }
-
- sbc.WriteToServer(dt);
-
-
- sqlbulkTransaction.Commit();
- res = true;
- }
- catch (SqlException ex)
- {
- res = false;
- sqlbulkTransaction.Rollback();
- }
-
- return res;
- }
- }
|