python批量更新mysql_使用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']]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值