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

时间:2015-01-02 14:07:06

标签: 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


使用上面的代码,数据库kuis中表Writer的第三行值用new_value更新,输出将行数更新:1
我怎么能同时更新多行?

3 个答案:

答案 0 :(得分:17)

可能您正在寻找cursor.executemany

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

答案 1 :(得分:3)

我不认为mysqldb有一种方法可以同时处理多个UPDATE查询。

但是你可以在最后使用ON DUPLICATE KEY UPDATE条件的INSERT查询。

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

@NgModule({
  declarations: [
    AppComponent,
    HostComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
    .
    .
    .
  ],
  bootstrap: [AppComponent],
  entryComponents: [
    SomeOtherEntryComponentsHere
  ]
})

export class AppModule {}

一个衬垫的说明

y2.domain([0, d3.max(dataByGroup, function(d) { return d3.sum(d.values, function(v) {return v.value;}); })]); //added

相同
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')

答案 2 :(得分:0)

我要写的最简单的是。

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)''' 
     

mycursor.executemany(sql,数据)

data = ['第1列的值','第2列的值',...,'第N列的值']