ADO.Net2.0中提供了SqlBulkCopy類
SqlBulkCopy 類
• DestinationTableName:目標數據庫的表名
• BulkCopyTimeout:指定操作完成的Timeout時間
• NotifyAfter:指定通知通知事件前處理的數據行數
• WriteToServer方法:將數據源拷備到目標數據庫
• SqlBulkCopy DesBulkOp = new
SqlBulkCopy(DesConString,
SqlBulkCopyOptions.UseInternalTransaction);
– 指定了目標數據庫,使用
SqlBulkCopyOptions.UseInternalTransaction是指遷移動作指定
在一個Transaction當中,如果數據遷移中產生錯誤或異常將發生
回滾。
• 使用SqlBulkCopy 類只能向SQL Server 表寫入數據。但
是,數據源不限於SQL Server;可以使用任何數據源,
只要數據可加載到DataTable 實例或可使用IDataReader
實例讀取數據。
C# code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
namespace Demo17
{
public partial class Form1 : Form
{
DateTime startTime;
public Form1()
{
InitializeComponent();
}
private void btnTest_Click(object sender, EventArgs e)
{
startTime = DateTime.Now;
string SrcConString;
string DesConString;
SqlConnection SrcCon = new SqlConnection();
SqlConnection DesCon = new SqlConnection();
SqlCommand SrcCom = new SqlCommand();
SqlDataAdapter SrcAdapter = new SqlDataAdapter();
DataTable dt = new DataTable();
SrcConString =
ConfigurationManager.ConnectionStrings["SrcDBConnectionString"].ConnectionString;
DesConString =
ConfigurationManager.ConnectionStrings["DesDBConnectionString"].ConnectionString;
SrcCon.ConnectionString = SrcConString;
SrcCom.Connection = SrcCon;
SrcCom.CommandText = " SELECT * From Production.Product";
SrcCom.CommandType = CommandType.Text;
SrcCom.Connection.Open();
SrcAdapter.SelectCommand = SrcCom;
SrcAdapter.Fill(dt);
SqlBulkCopy DesBulkOp;
DesBulkOp = new SqlBulkCopy(DesConString,
SqlBulkCopyOptions.UseInternalTransaction);
DesBulkOp.BulkCopyTimeout = 500000000;
DesBulkOp.SqlRowsCopied +=
new SqlRowsCopiedEventHandler(OnRowsCopied);
DesBulkOp.NotifyAfter = dt.Rows.Count;
//DesBulkOp.ColumnMappings.Add("SrcCol", "DesCol");
try
{
DesBulkOp.DestinationTableName = "Product";
DesBulkOp.WriteToServer(dt);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
SrcCon.Close();
DesCon.Close();
}
}
private void OnRowsCopied(object sender, SqlRowsCopiedEventArgs args)
{
lblCounter.Text += args.RowsCopied.ToString() + " rows are copied/r/n";
TimeSpan copyTime = DateTime.Now - startTime;
lblCounter.Text += "Copy Time:" + copyTime.Seconds.ToString() + "." + copyTime.Milliseconds.ToString() + " seconds";
}
}
}