C#批量保存方法-利用Net SqlBulkCopy 批量导入数据库,速度超快-通用方法源码提供

#region public void SqlBulkCopyData(DataTable dataTable) 利用Net SqlBulkCopy 批量导入数据库,速度超快
        /// <summary>
        /// 利用Net SqlBulkCopy 批量导入数据库,速度超快
        /// </summary>
        /// <param name="dataTable">源内存数据表</param>
        public void SqlBulkCopyData(DataTable dataTable)
        {
            // SQL 数据连接
            SqlConnection sqlConnection = null;
            // 打开数据库
            this.Open();
            // 获取连接
            sqlConnection = (SqlConnection)GetDbConnection();
            using (SqlTransaction tran = sqlConnection.BeginTransaction())
            {
                // 批量保存数据,只能用于Sql
                SqlBulkCopy sqlbulkCopy = new SqlBulkCopy(sqlConnection, SqlBulkCopyOptions.Default, tran);
                // 设置源表名称
                sqlbulkCopy.DestinationTableName = dataTable.TableName;
                // 设置超时限制
                sqlbulkCopy.BulkCopyTimeout = 1000;

                foreach (DataColumn dtColumn in dataTable.Columns)
                {
                    sqlbulkCopy.ColumnMappings.Add(dtColumn.ColumnName, dtColumn.ColumnName);
                }
                try
                {
                    // 写入
                    sqlbulkCopy.WriteToServer(dataTable);
                    // 提交事务
                    tran.Commit();
                }
                catch
                {
                    tran.Rollback();
                    sqlbulkCopy.Close();
                }
                finally
                {
                    sqlbulkCopy.Close();
                    this.Close();
                }
            }
        }
        #endregion

作者:王春天 地址:http://www.cnblogs.com/spring_wang/

posted @ 2013-05-12 15:17  王春天  阅读(986)  评论(0编辑  收藏  举报
云推荐