datatable中有大量数据(>50万),怎样使它快速导入到一个已存在的SQLSERVER表中?
RT,不想基于ROWS一条条做INSERT,那样太慢了,50万条要等老半天,不知道有什么命令可以直接导入?
------解决方案--------------------2.0 中
sqlbulkcopy
------解决方案--------------------测试代码:
DateTime startTime;
protected void Button1_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 [SrcTable] ";
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;
try
{
DesBulkOp.DestinationTableName = "SrcTable ";
DesBulkOp.WriteToServer(dt);
}
catch (Exception ex)
{
lblResult.Text = ex.Message;
}
finally
{
SrcCon.Close();
DesCon.Close();
}
}
private void OnRowsCopied(object sender, SqlRowsCopiedEventArgs args)
{
lblCounter.Text += args.RowsCopied.ToString() + " rows are copied <Br> ";
TimeSpan copyTime = DateTime.Now - startTime;
lblCounter.Text += "Copy Time: " + copyTime.Seconds.ToString() + ". " + copyTime.Milliseconds.ToString() + " seconds ";
}
代码说明:
SqlBulkCopy DesBulkOp;
DesBulkOp = new SqlBulkCopy(DesConString, SqlBulkCopyOptions.UseInternalTransaction);先生成SqlBulkCopy 实例,构造函数指定了目标数据库,使用SqlBulkCopyOptions.UseInternalTransaction是指迁移动作指定在一个Transaction当中,如果数据迁移中产生错误或异常将发生回滚。
WriteToServer方法就是将数据源拷备到目标数据库。在使用WriteToServer方法之前必须先指定DestinationTableName属性,也就是目标数据库的表名,
这种方式我用上了,速度很快!我现在把代码贴出来.希望能帮到您...
^o^