批量插入或更新数据

/// <summary>
        /// 大数据单表批量插入,带事务
        /// </summary>
        /// <param name="keepID"></param>
        /// <param name="tableName"></param>
        /// <param name="dt"></param>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        public static bool MsSqlBulkCopyInsert(bool keepID, string tableName, DataTable dt, ref string msg, string connectionString = null)
        {
            if (dt == null || dt.Rows.Count <= 0)
            {
                msg = "找不到数据";
                return true;
            }
            using (SqlConnection conn = string.IsNullOrWhiteSpace(connectionString) ? new SqlConnection(MSSQLHelper.connectionString) : new SqlConnection(connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        using (SqlBulkCopy sbc = new SqlBulkCopy(conn, (keepID ? SqlBulkCopyOptions.KeepIdentity : SqlBulkCopyOptions.Default) | SqlBulkCopyOptions.FireTriggers, trans))
                        {
                            sbc.BatchSize = dt.Rows.Count;   //每一批次中的行数
                            //Bulkcopy 无法判断数据是否已经存在,如果在bulkcopy时发生数据库返回错误,此次的bulkcopy操作会rollback。建议在数据库中添加临时表,bulkcopy的destination设置为临时表,bulkcopy完成后运行从临时表到真正表的插入操作,筛选duplicate数据并删除
                            sbc.DestinationTableName = string.Concat("[", tableName + "]");
                            sbc.BulkCopyTimeout = 300;//超时之前操作完成所允许的秒数,大批量数量需要的时长5分钟。 报错:“超时时间已到。在操作完成之前超时时间已过或服务器未响应
                            foreach (DataColumn column in dt.Columns)
                            {
                                sbc.ColumnMappings.Add(column.ColumnName, column.ColumnName);
                            }
                            sbc.WriteToServer(dt);
                            trans.Commit();
                            return true;
                        }
                    }
                    catch (Exception err)
                    {
                        trans.Rollback();//回滚事务
                        msg = err.Message;
                    }
                }
            }
            return false;
        }

/// <summary>
        /// 大数据多表批量插入,带事务
        /// </summary>
        /// <param name="keepID"></param>
        /// <param name="tableName"></param>
        /// <param name="dt"></param>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        public static bool MsSqlBulkCopyManyInsert(bool keepID, Dictionary<string, DataTable> dic, ref string msg, string connectionString = null)
        {
            if (dic == null || dic.Count <= 0)
            {
                msg = "找不到数据";
                return true;
            }
            using (SqlConnection conn = string.IsNullOrWhiteSpace(connectionString) ? new SqlConnection(MSSQLHelper.connectionString) : new SqlConnection(connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        using (SqlBulkCopy sbc = new SqlBulkCopy(conn, (keepID ? SqlBulkCopyOptions.KeepIdentity : SqlBulkCopyOptions.Default) | SqlBulkCopyOptions.FireTriggers, trans))
                        {
                            foreach (var item in dic)
                            {
                                string tableName = item.Key;
                                DataTable dt = item.Value;
                                if (dt == null || dt.Rows.Count <= 0)
                                {
                                    continue;
                                }
                                sbc.BatchSize = dt.Rows.Count;   //每一批次中的行数
                                                                 //Bulkcopy 无法判断数据是否已经存在,如果在bulkcopy时发生数据库返回错误,此次的bulkcopy操作会rollback。建议在数据库中添加临时表,bulkcopy的destination设置为临时表,bulkcopy完成后运行从临时表到真正表的插入操作,筛选duplicate数据并删除
                                sbc.DestinationTableName = string.Concat("[", tableName + "]");
                                sbc.BulkCopyTimeout = 300;//超时之前操作完成所允许的秒数,大批量数量需要的时长5分钟。 报错:“超时时间已到。在操作完成之前超时时间已过或服务器未响应
                                sbc.ColumnMappings.Clear();
                                foreach (DataColumn column in dt.Columns)
                                {
                                    sbc.ColumnMappings.Add(column.ColumnName, column.ColumnName);
                                }
                                sbc.WriteToServer(dt);
                            }
                            trans.Commit();
                            return true;
                        }
                    }
                    catch (Exception err)
                    {
                        trans.Rollback();//回滚事务
                        msg = err.Message;
                        return false;
                    }
                }
            }
        }

/// <summary>
        /// 大数据批量更新
        /// </summary>
        /// <param name="table"></param>
        /// <param name="tableName"></param>
        /// <param name="limitWhere"></param>
        /// <param name="onceUpdateNumber"></param>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        public static int MsSqlUpdate(DataTable table, string tableName, string limitWhere, int onceUpdateNumber = 5000, string connectionString = null)
        {

int result = -1;
            SqlConnection conn = new SqlConnection(string.IsNullOrWhiteSpace(connectionString) ? MSSQLHelper.connectionString :connectionString);
            SqlCommand comm = conn.CreateCommand();
            comm.CommandType = CommandType.Text;
            SqlDataAdapter adapter = new SqlDataAdapter(comm);
            SqlCommandBuilder commandBulider = new SqlCommandBuilder(adapter);
            commandBulider.ConflictOption = ConflictOption.OverwriteChanges;
            try
            {
                conn.Open();
                //设置批量更新的每次处理条数
                adapter.UpdateBatchSize = table.Rows.Count;
                adapter.SelectCommand.Transaction = conn.BeginTransaction();
                adapter.SelectCommand.CommandText = string.Format("select * from {0} where {1}", string.IsNullOrWhiteSpace(tableName) ? table.TableName : tableName, limitWhere);
                result = adapter.Update(table);
                adapter.SelectCommand.Transaction.Commit();/////提交事务
            }
            catch (Exception ex)
            {
                if (adapter.SelectCommand != null && adapter.SelectCommand.Transaction != null)
                {
                    adapter.SelectCommand.Transaction.Rollback();
                }
                throw ex;
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }
            return result;
        }

时间: 2024-11-15 09:03:27

批量插入或更新数据的相关文章

Java批量插入、更新数据

Java的批量添加数据,多个字段同时添加多条数据,我不知道你遇到过没有.今天我们就以一个具体的实例来说一下Java的批量添加数据,面向的是Oracle数据库. 前台页面: <span style="font-size:14px;"><body class="main_body" scroll="no"> <div class="employee_gun_dong"> <form nam

Mysql游标使用 批量插入或更新数据

-- LOOP循环 CREATE PROCEDURE `test`.`new_procedure` () BEGIN -- 需要定义接收游标数据的变量 DECLARE a CHAR(16); -- 游标 DECLARE cur CURSOR FOR SELECT i FROM test.t; -- 遍历数据结束标志 DECLARE done INT DEFAULT FALSE; -- 将结束标志绑定到游标 DECLARE CONTINUE HANDLER FOR NOT FOUND SET do

C#使用SqlDataAdapter 实现数据的批量插入和更新

近日由于项目要求在需要实现中型数据的批量插入和更新,晚上无聊,在网上看到看到这样的一个实现方法,特摘抄过来,以便以后可能用到参考. 一.数据的插入 DateTime begin = DateTime.Now; string connectionString = ......; using(SqlConnection conn = new SqlConnection(connectionString)){ conn.Open(); SqlDataAdapter sd = new SqlDataAd

Asp.net QueryString批量插入和更新

public static string InsertOrUpdateQueryString(string[] keys, string[] values) { return InsertOrUpdateQueryString(System.Web.HttpContext.Current.Request, keys, values); } public static string InsertOrUpdateQueryString(System.Web.HttpRequest request,

SQL语句-批量插入表(表数据插表)

批量插入表(表数据插表) ****1.INSERT INTO SELECT语句语句形式为:Insert into Table2(field1,field2,...) select value1,value2,... from Table1要求目标表Table2必须存在,由于目标表Table2已经存在,所以我们除了插入源表Table1的字段外,还可以插入常量.示例如下: 2.SELECT INTO FROM语句语句形式为:SELECT vale1, value2 into Table2 from

java批量插入或更新的问题

在批量插入或者更新中,setXXX的时候字段类型必须一致.例如:在普通sql中 pstmt8.setBigDecimal(j ,xxx);可以写成pstmt8.setString(j,xxx.toString()); 但在批量插入时必须写成pstmt8.setBigDecimal(j,xxx);否则批处理会报提交中至少有一条不成功的问题.折腾一下午,终于搞好了.顺便记下来,方便参考.

mysql命令行批量插入100条数据命令

先介绍一个关键字的使用: delimiter 定好结束符为"$$",(定义的时候需要加上一个空格) 然后最后又定义为";", MYSQL的默认结束符为";" 如何通过mysql命令行批量插入100条数据呢,可以在代码里实现,也可以通过命令行,也就是通过存储过程: delimiter $$create procedure myproc ()begindeclare num int ;set num = 1 ;while num < 100 d

Mybatis 批量插入多条数据,使用场景:导入多条数据

Mybatis 批量插入多条数据,使用场景:导入多条数据 接口代码: void batchInsertCapacity(@Param("list")List<Map<String, Object>> metadbmaplist); SQL: <insert id="batchInsertCapacity"> insert into index_prodcut ( ID, ORG_ID, TEXT1, TEXT2, TEXT3, P

Mybatis+Oracle进行数据的批量插入和更新

项目中会遇到这样的情况,查询出多条记录(一个List对象集合),一次性要插入多条数据到数据库中,下面就拿Data类来看看两种插入方法: 方法一: Mybatis本身只支持逐条插入,比较笨的方法,就是遍历一个List,循环中逐条插入,比如下面这段代码 <pre class="java" style="margin-top: 0px; margin-bottom: 10px; box-sizing: border-box; overflow: auto; font-fami