· ASP.NET(C#)SqlBulkCopy批量的快速插入数据
SqlBulkCopy把DataTable,DataReader数据快速插入到数据库,数据迁移很快捷
privatestatic readonly string connStr = ConfigurationManager.ConnectionStrings["myConnStr"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//ASP.NET(C#)SqlBulkCopy批量的快速插入数据
DateTime start = DateTime.Now;
Response.Write(start.ToString("HH:mm:ss:fff"));
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("name", typeof(string));
for (int i = 0; i < 10000; i++)
{
DataRow row = dt.NewRow();
row["name"] = i.ToString();
dt.Rows.Add(row);
}
conn.Open();
using (SqlBulkCopy copy = new SqlBulkCopy(conn))
{
copy.BatchSize = 100;//每次插入的记录数
copy.BulkCopyTimeout = 60;//超时之前操作完成所允许的秒数
copy.NotifyAfter = 1000;//在生成通知事件之前要处理的行数
copy.SqlRowsCopied += new SqlRowsCopiedEventHandler(copy_SqlRowsCopied);//每次处理完NotifyAfter属性指定的行数时发生
copy.DestinationTableName = "bulktest";
//DataTable与数据表的字段名称对应(数据迁移到时候,可以解决表字段名称不一样)
copy.ColumnMappings.Add("id", "id");
copy.ColumnMappings.Add("name", "title");
copy.WriteToServer(dt);
}
conn.Dispose();
DateTime end = DateTime.Now;
Response.Write("<br />" + end.ToString("HH:mm:ss:fff"));
TimeSpan ts = end - start;
Response.Write("<br />所需时间:" + ts.TotalSeconds.ToString());
}
}
void copy_SqlRowsCopied(object sender, SqlRowsCopiedEventArgs e)
{
Response.Write("<br />成功插入1000条");
}
<connectionStrings>
<addname="myConnStr"connectionString="Data Source=.;Initial Catalog=Study;User Id=sa;Password=sa;"/>
</connectionStrings>