如何在python中使用单个MySQL查询更新多行?

Tec*_*ola 8 python mysql mysql-python

#!/usr/bin/python

# -*- coding: utf-8 -*-
import MySQLdb as mdb

con = mdb.connect('localhost', 'root', 'root', 'kuis')

with con:

    cur = con.cursor()
    cur.execute("UPDATE Writers SET Name = %s WHERE Id = %s ",
        ("new_value" , "3"))
    print "Number of rows updated:",  cur.rowcount
Run Code Online (Sandbox Code Playgroud)


使用上面的代码,数据库kuis中表Writer的第三行值用new_value更新,输出将是Number od行更新:1
我应该如何同时更新多行?

Pet*_*Mmm 18

可能你正在寻找cursor.executemany.

cur.executemany("UPDATE Writers SET Name = %s WHERE Id = %s ",
        [("new_value" , "3"),("new_value" , "6")])
Run Code Online (Sandbox Code Playgroud)


Wes*_*ite 8

我不认为 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()
Run Code Online (Sandbox Code Playgroud)

一个班轮的解释

columns = ', '.join('`{}`'.format(k) for k in data_dict)
Run Code Online (Sandbox Code Playgroud)

是相同的

column_list = []
for k in data_dict:
    column_list.append(k)
columns = ", ".join(columns)
Run Code Online (Sandbox Code Playgroud)

这是一个使用示例

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

update_many(data_list=test_data_list, mysql_table='writers')
Run Code Online (Sandbox Code Playgroud)

查询输出

INSERT INTO writers (`articles`, `id`, `name`) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE articles=VALUES(articles), id=VALUES(id), name=VALUES(name)
Run Code Online (Sandbox Code Playgroud)

值输出

[[1, 1, 'Tech'], [8, 2, 'Jhola'], [0, 3, 'Wes']]
Run Code Online (Sandbox Code Playgroud)

  • 这个答案对我有用。我调整它以与 mysql.connector 一起使用。对于 Python 3.8,我还必须将 `data_dict.values()` 更改为 `list( data_dict.values())`。我还需要包含所有列(不确定是否因为数据库限制需要这样做?)。我在一分钟内在远程服务器上完成了大约 5 万次数据转换和更新。现在有一些大桌子。 (2认同)