1. 程式人生 > 其它 >mysql executemany與 insert ... ON DUPLICATE KEY UPDATE 一起使用

mysql executemany與 insert ... ON DUPLICATE KEY UPDATE 一起使用

MySQLdb(Python)executemany和ON DUPLICATE KEY UPDATE的使用問題


在將executemany()和“ON DUPLICATE KEY UPDATE”聯合起來使用時需要注意一個小問題。
假設在資料庫中有一個表A,其各個欄位如下所示:
欄位型別id (關鍵字)CHAR(8)last_dateDATEcountINT(11)
現在我們要想向表中批量插入資料:若關鍵字存在則更新last_date並將count累加。則sql應該如下書寫:
# 省略imports和建立資料庫連線的程式碼

# 省略imports和建立資料庫連線的程式碼
data_items = [['1', '2015-06-05', 10], ['2', '2015-06-05', 20], ...]

sql = 'insert into A (id, last_date, count) values(%s, %s, %s) on 
duplicate key update last_date=values(last_date),count=count+values(count)'

try:
    with closing(connection.cursor()) as cursor:
        cursor.executemany(sql, info_tuple)
        connection.commit()
except MySQLdb.Error, e: print("Mysql Error %d: %s" % (e.args[0], e.args[1]))

注意這裡的sql變數不能按照常規模式書寫,即:
# 省略imports和建立資料庫連線的程式碼

# 省略imports和建立資料庫連線的程式碼
data_items = [['1', '2015-06-05', 10, '2015-06-05', 10], 
              ['2', '2015-06-05', 20, '2015-06-05', 20], ...]

sql = 'insert into A (id, last_date, count) values(%s, %s, %s) 
on duplicate key update last_date=%s, count=count+%s' ......

否則會報如下錯誤:

TypeError: not all arguments converted during string formatting.
————————————————
版權宣告:本文為CSDN博主「yongyuandeie」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處連結及本宣告。
原文連結:https://blog.csdn.net/yongyuandeie/article/details/46381307