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

如何在python中使用单个MySQL查询更新多行?,python,mysql,mysql-python,Python,Mysql,Mysql Python,使用上述代码,数据库kuis中表写入器的第三行值将用新的_值更新,并且输出将更新的od行数:1 我应该如何同时更新多行?您可能正在寻找 我不认为mysqldb有一种同时处理多个更新查询的方法 但是,您可以使用一个插入查询,该查询的末尾带有重复的密钥更新条件 为了便于使用和可读,我编写了以下示例 cur.executemany("UPDATE Writers SET Name = %s WHERE Id = %s ", [("new_value" , "3"),("new_valu


使用上述代码,数据库kuis中表写入器的第三行值将用新的_值更新,并且输出将更新的od行数:1

我应该如何同时更新多行?

您可能正在寻找


我不认为mysqldb有一种同时处理多个更新查询的方法

但是,您可以使用一个插入查询,该查询的末尾带有重复的密钥更新条件

为了便于使用和可读,我编写了以下示例

cur.executemany("UPDATE Writers SET Name = %s WHERE Id = %s ",
        [("new_value" , "3"),("new_value" , "6")])
解释一行程序

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' : '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')
值输出

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

我要写的最简单的一条就是

sql=''插入(第1列,第2列,…,第N列)
值(%s,%s,…%s)
在重复键更新时,column1=值(第1列),column3=值(第N列)“”
mycursor.executemany(sql,数据)


data=['value of column 1','value of column 2',…,'value of column']

更改您的
WHERE
语句以匹配多个条件?可能是cursor.execute('update sql…',multi=True)?@algosig,您想用
“new_values”=3更新多行,还是用不同的“new_value”更新多个sql?@Anzel我想更新第三行中的“汤姆”,即“3”和第四行中的“山姆”,即“4”,是否可以使用单cur.execute(…)查询还是我应该多次使用同一命令?我的注释和@petermm的答案都适用于您我得到了结果,但为什么更新的行数仍然相同,即更新两个字段时1应该是2?@algosig,这是因为在执行级别上,直到您执行
conn.commit()之前,没有数据库提交
,这就是你要求执行官的全部目的,不是吗?@petermm,谢谢你。你能帮我查询一下吗。Qry-“Update mytable SET status='new status'where id in()”@John
cur.executemany(“Update mytable SET status=%s where id=%s”),[((“new status”,“3”),(“new status”,“6”))
FYI供相关方参考-如果出现语法错误,请尝试使用引号字符(甚至删除它们),但无法找出原因。我使用单引号表示字符串值,但切换到双引号或甚至没有引号似乎开始起作用(不确定这是否值得一个新问题),实际上有一个引号,并且在您的答案上方解释了它。希望您也能从中受益;)这个答案节省了我很多时间。我用第一个答案更新了一个庞大的表格,花了好几个小时。对于相同的查询,使用重复键插入只需要大约一分钟。mysql页面解释了原因:“在大多数情况下,executemany()方法迭代参数序列,每次都将当前参数传递给execute()方法。”
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, 'Tech'], [8, 2, 'Jhola'], [0, 3, 'Wes']]
sql='''INSERT INTO <Tabel Name> (column 1, column 2, ... , column N)
 VALUES (%s, %s, ..., %s) 
ON DUPLICATE KEY UPDATE column1=VALUES(column 1), column3=VALUES(column N)'''