mysql-批量更新

方法一:用update结合case、then实现

原始SQL语句

UPDATE baginfo_2021_09 
    SET channel_id = CASE id 
        WHEN 1 THEN 3 
        WHEN 2 THEN 4 
        WHEN 3 THEN 5 
    END, 
    stationId = CASE id 
        WHEN 1 THEN 6
        WHEN 2 THEN 7
        WHEN 3 THEN 8
    END
WHERE id IN (1,2,3)

mybatis写法

    <update id="updateBatchCaseThen" parameterType="java.util.List">
        update baginfo_2022_03
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="clientId =case" suffix="end,">
                <foreach collection="list" item="i" index="index">
                    <if test="i.clientId!=null">
                        when id=#{i.id} then #{i.clientId}
                    </if>
                </foreach>
            </trim>
            <trim prefix="model_version =case" suffix="end,">
                <foreach collection="list" item="i" index="index">
                    <if test="i.model_version!=null">
                        when id=#{i.id} then #{i.model_version}
                    </if>
                </foreach>
            </trim>
            <trim prefix="create_time =case" suffix="end,">
                <foreach collection="list" item="i" index="index">
                    <if test="i.create_time!=null">
                        when id=#{i.id} then #{i.create_time}
                    </if>
                </foreach>
            </trim>
        </trim>
        where
        <foreach collection="list" separator="or" item="i" index="index">
            id=#{i.id}
        </foreach>
    </update>

方法二:用foreach循环实现

mybatis写法

    <update id="batchUpdateBagInfo" parameterType="com.example.demo.entity.BagInfo">
        <foreach collection="list" item="item" index="index" open="" close="" separator=";">
            update baginfo_2022_03
            <set>
                <if test="item.clientId != null">
                    clientId = #{item.clientId},
                </if>
                <if test="item.model_version != null">
                    model_version = #{item.model_version},
                </if>
                <if test="item.create_time != null">
                    create_time = #{item.create_time},
                </if>
            </set>
            where id = #{item.id}
        </foreach>
    </update>

用这种方法时,yml文件中配置的数据库URL,需要加上&allowMultiQueries=true

性能比较

mysql表数据量:2000w;一次更新数据量:1000

更新方法更新总耗时
单条循环更新(for)1-3s
方法1110ms-180ms
方法2110ms-180ms

总体比较,单条循环更新最慢的,想想也知道。而方法1和方法2的耗时相差不大。更高数量的批量更新,可能会导致结果不同,这里暂时没有测试。

### 使用 mysql-connector-python 进行批量更新数据的方法 为了高效地完成大量数据的更新操作,可以利用 `executemany()` 方法。此方法允许一次性执行多次相同的 SQL 语句,并传入不同的参数集,从而减少网络开销并提高效率。 #### 1. 创建连接与游标 首先按照标准流程创建到 MySQL 数据库的连接以及相应的游标对象: ```python import mysql.connector from mysql.connector import Error def create_connection(host_name, user_name, user_password, db_name): connection = None try: connection = mysql.connector.connect( host=host_name, user=user_name, passwd=user_password, database=db_name ) print("Connection to MySQL DB successful") except Error as e: print(f"The error '{e}' occurred") return connection ``` #### 2. 编写批量更新逻辑 定义一个函数用于执行批量更新操作,在该函数内部调用 `executemany()` 方法传递预编译好的 SQL 更新语句及其对应的参数列表。 ```python def bulk_update_data(connection, sql_query, data_list): cursor = connection.cursor() try: cursor.executemany(sql_query, data_list) connection.commit() # 提交更改至数据库 print(f"{cursor.rowcount} records were updated successfully.") except Error as e: print(f"Error during update operation: {e}") finally: cursor.close() ``` #### 3. 实际应用案例 假设有一个名为 `employees` 的表,其结构如下所示: | id | name | salary | |----|----------|--------| | 1 | Alice | 50000 | | 2 | Bob | 60000 | 现在想要调整部分员工薪水,则可按以下方式进行编码: ```python connection = create_connection("localhost", "root", "mypassword", "mydb") sql_update_query = """UPDATE employees SET salary = %s WHERE id = %s""" data_to_update = [ (70000, 1), (80000, 2) ] bulk_update_data(connection, sql_update_query, data_to_update) if connection.is_connected(): connection.close() print("MySQL connection is closed.") ``` 在这个例子中,我们准备了一个包含新薪资水平和对应雇员ID的二维数组作为输入给定至 `executemany()` 函数。这样就可以一次性的对多条记录实施修改动作[^3]。 --- ### 总结 通过以上步骤展示了如何采用 `mysql-connector-python` 库来进行高效的批量数据更新作业。这种方法不仅简化了代码编写过程还提升了运行效能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值