溶入海洋中的雨滴
将自己溶入大海,化作一阵清风
  #region  批量插入数据到数据库
            DateTime startTime; 
            private bool SqlBulkCopy(DataTable dt)
            {

                try
                {
                    startTime = DateTime.Now;
                    //数据批量导入sqlserver,创建实例    SqlBulkCopyOptions.UseInternalTransaction采用事务  复制失败自动回滚
                    System.Data.SqlClient.SqlBulkCopy sqlbulk = new System.Data.SqlClient.SqlBulkCopy(System.Configuration.ConfigurationSettings.AppSettings["ConStr"], SqlBulkCopyOptions.UseInternalTransaction);
                    sqlbulk.SqlRowsCopied +=
                    new SqlRowsCopiedEventHandler(OnRowsCopied); //订阅复制完成后的方法,参数是 sqlbulk.NotifyAfter的值
                    sqlbulk.NotifyAfter = dt.Rows.Count;

                    //目标数据库表名
                    sqlbulk.DestinationTableName = "T_TempUpLoadTC";
                    //数据集字段索引与数据库字段索引映射
                    sqlbulk.ColumnMappings.Add(0, "userName");
                    sqlbulk.ColumnMappings.Add(1, "JiFenCount");
                    //导入
                    sqlbulk.WriteToServer(dt);
                    sqlbulk.Close();
                    return true;
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                finally 
                {
                    dt.Dispose();
                }
            }
        

            //复制完成后的处理事件
            private void OnRowsCopied(object sender, SqlRowsCopiedEventArgs args)
            {
                lblCounter.Text += args.RowsCopied.ToString() + " 条记录已导入";
                TimeSpan copyTime = DateTime.Now - startTime;
                lblCounter.Text += "  花费时间:" + copyTime.Seconds.ToString() + "." +
                copyTime.Milliseconds.ToString() + " 秒";
            }
          #endregion
posted on 2008-06-26 22:56  溶入海洋中的雨滴  阅读(5909)  评论(0编辑  收藏  举报