欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SqlBulkCopy大数据复制插入数据

程序员文章站 2022-04-02 16:13:02
...

public partial class ASP_NET : System.Web.UI.Page
{
    private DateTime startTime;
	string connString = "";//数据库连接

    protected void Button1_Click(object sender, EventArgs e)
    {
        startTime = DateTime.Now;
        SqlConnection srcConnection = new SqlConnection();
		srcConnection.ConnectionString = connString;
		
        SqlCommand sqlcmd = new SqlCommand();                   
        sqlcmd.Connection = srcConnection;
        sqlcmd.CommandText = "select * from abc"; //将这个表的数据复制到"bcd"表中
        sqlcmd.CommandType = CommandType.Text;
        sqlcmd.Connection.Open();
		
		DataTable dt = new DataTable(); 
		SqlDataAdapter da = new SqlDataAdapter();   
        da.SelectCommand = sqlcmd;	 
        da.Fill(dt);

        SqlBulkCopy sbc = new SqlBulkCopy(connString,SqlBulkCopyOptions.UseInternalTransaction); //支持事物
        sbc.BulkCopyTimeout = 5000;
        sbc.SqlRowsCopied +=new SqlRowsCopiedEventHandler(OnRowsCopied);
        sbc.NotifyAfter = dt.Rows.Count;
        try
        {
            sbc.DestinationTableName = "bcd";
            sbc.WriteToServer(dt); //开始复制数据
        }
        catch (Exception ex)
        {
            lblCounter.Text = ex.Message.ToString();
        }
        finally
        {
            sqlcmd.Clone();
            srcConnection.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";
    }
}

相关标签: java