例1:
private void BulkInsert()
{
SqlConnection sqlcon = new SqlConnection("Data Source=LocalHost;Integrated Security=SSPI;Initial Catalog=xiaotest;");
DateTime beginTime = DateTime.Now;
DataTable dt = new DataTable();
dt.Columns.Add("n", typeof(string));
dt.Columns.Add("name", typeof(string));
for (int i = 1; i <</SPAN> 1000; i++)
{
DataRow r = dt.NewRow();
r["n"] = i;
r["name"] = "xiao";
dt.Rows.Add(r);
}
sqlcon.Open();
using (SqlBulkCopy bulk = new SqlBulkCopy("Data Source=LocalHost;Integrated Security=SSPI;Initial Catalog=xiaotest;"))
{
bulk.BatchSize = 1000;
bulk.DestinationTableName = "test2";
bulk.ColumnMappings.Add("n", "n");
bulk.ColumnMappings.Add("name", "name");
bulk.WriteToServer(dt);
}
DateTime endTime = DateTime.Now;
TimeSpan useTime = endTime - beginTime;
dt.Dispose();
time = "使用时间" + useTime.TotalSeconds.ToString() + "秒";
sqlcon.Close();
sqlcon.Dispose()
例2:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace WFM_SANY_SPDM
{
public class SqlBulk
{
public void InsertTable(DataTable dt, string TabelName,DataColumnCollection dtColum)
{
string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
//声明数据库连接
SqlConnection conn = new SqlConnection(str);
conn.Open();
//声明SqlBulkCopy ,using释放非托管资源
using (SqlBulkCopy sqlBC = new SqlBulkCopy(conn))
{
//一次批量的插入的数据量
sqlBC.BatchSize = 1000;
//超时之前操作完成所允许的秒数,如果超时则事务不会提交 ,数据将回滚,所有已复制的行都会从目标表中移除
sqlBC.BulkCopyTimeout = 60;
//設定 NotifyAfter 属性,以便在每插入10000 条数据时,呼叫相应事件。
sqlBC.NotifyAfter = 10000;
// sqlBC.SqlRowsCopied += new SqlRowsCopiedEventHandler(OnSqlRowsCopied);
//设置要批量写入的表
sqlBC.DestinationTableName =TabelName;
//自定义的datatable和数据库的字段进行对应
//sqlBC.ColumnMappings.Add("id", "tel");
//sqlBC.ColumnMappings.Add("name", "neirong");
for (int i = 0; i < dtColum.Count; i++)
{
sqlBC.ColumnMappings.Add(dtColum[i].ColumnName.ToString(), dtColum[i].ColumnName.ToString());
}
//批量写入
sqlBC.WriteToServer(dt);
}
conn.Dispose();
}
//响应时事件
void OnSqlRowsCopied(object sender, SqlRowsCopiedEventArgs e)
{
// Response.Write("<br/> OK! ");
}
}
}