mysql - 用python批量更新MySql

标签 mysql python-2.7 mysql-connector-python

我必须将数百万行更新到 MySQL 中。我目前正在使用 for 循环来执行查询。为了加快更新速度,我想使用 executemany() Python MySQL 连接器,这样我就可以对每个批处理使用单个查询来分批更新。

最佳答案

我认为 mysqldb 无法同时处理多个 UPDATE 查询。

但是您可以在末尾使用带有 ON DUPLICATE KEY UPDATE 条件的 INSERT 查询。

为了易用性和可读性,我编写了以下示例。

import MySQLdb

def update_many(data_list=None, mysql_table=None):
    """
    Updates a mysql table with the data provided. If the key is not unique, the
    data will be inserted into the table.

    The dictionaries must have all the same keys due to how the query is built.

    Param:
        data_list (List):
            A list of dictionaries where the keys are the mysql table
            column names, and the values are the update values
        mysql_table (String):
            The mysql table to be updated.
    """

    # Connection and Cursor
    conn = MySQLdb.connect('localhost', 'jeff', 'atwood', 'stackoverflow')
    cur = conn.cursor()

    query = ""
    values = []

    for data_dict in data_list:

        if not query:
            columns = ', '.join('`{0}`'.format(k) for k in data_dict)
            duplicates = ', '.join('{0}=VALUES({0})'.format(k) for k in data_dict)
            place_holders = ', '.join('%s'.format(k) for k in data_dict)
            query = "INSERT INTO {0} ({1}) VALUES ({2})".format(mysql_table, columns, place_holders)
            query = "{0} ON DUPLICATE KEY UPDATE {1}".format(query, duplicates)

        v = data_dict.values()
        values.append(v)

    try:
        cur.executemany(query, values)
    except MySQLdb.Error, e:
        try:
            print"MySQL Error [%d]: %s" % (e.args[0], e.args[1])
        except IndexError:
            print "MySQL Error: %s" % str(e)

        conn.rollback()
        return False

    conn.commit()
    cur.close()
    conn.close()

对一行的解释

columns = ', '.join('`{}`'.format(k) for k in data_dict)

相同
column_list = []
for k in data_dict:
    column_list.append(k)
columns = ", ".join(columns)

这是一个用法示例

test_data_list = []
test_data_list.append( {'id' : 1, 'name' : 'Marco', 'articles' : 1 } )
test_data_list.append( {'id' : 2, 'name' : 'Keshaw', 'articles' : 8 } )
test_data_list.append( {'id' : 3, 'name' : 'Wes', 'articles' : 0 } )

update_many(data_list=test_data_list, mysql_table='writers')

查询输出

INSERT INTO writers (`articles`, `id`, `name`) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE articles=VALUES(articles), id=VALUES(id), name=VALUES(name)

值输出

[[1, 1, 'Marco'], [8, 2, 'Keshaw'], [0, 3, 'Wes']]

关于mysql - 用python批量更新MySql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37006202/

相关文章:

mysql - 更新(选择...)设置...

mysql - 如何禁用Mysql复制日志?

mysql - 两个查询的执行是否有可能相互干扰

python - 围绕空格分割字符串,中间不使用冒号

python - Python 导入后自动实例化类

python - 如何不解压查询返回的所有内容?

MySQL - 将表合并为一个

python - 如果我用re.findall 怎么注册才能不分开点

python - 导入错误: No module named authentication

python - 使用 Python 在 Pi 启动时写入 MySQL 数据库