使用executemany對數(shù)據(jù)進行批量插入的話,要注意一下事項:
#coding:utf8conn = MySQLdb.connect(host = “l(fā)ocalhost”, user = “root”, passwd = “123456”, db = “myDB”)cursor = conn.cursor()sql = “insert into myTable (created_day,name,count) values(%s,%s,%s) ON DUPLICATE KEY UPDATE count=count+values(count)”args=[("2012-08-27","name1",100),("2012-08-27","name1",200),("2012-08-27","name2",300)]try: cursor.executemany(sql, args)except Exception as e: print0(“執(zhí)行MySQL: %s 時出錯:%s” % (sql, e))finally: cursor.close() conn.commit() conn.close()這里args是一個包含多個元組的數(shù)組,每個元組對應mysql當中的一條數(shù)據(jù),注意這里的created_day對應的%s沒有引號。這里推測executemany自己首先對sql語句進行正則匹配%s然后在此基礎(chǔ)上,對字符串進行嵌入處理,如果這里%s加上引號的話,插入mysql當中會出現(xiàn)”0000-00-00″類型的錯誤日期。
如果一次性要插入很多條數(shù)據(jù)的話,在這里強烈 推薦使用executemany,從自己體會來講,一條一條的insert需要2-3個小時時間的數(shù)據(jù)插入,使用executemany只需要2-3秒!!!
在這里executemany和ON DUPLICATE KEY UPDATE聯(lián)合使用的時候如果按照sql常規(guī)模式,即:sql=”insert into myTable (created_day,name,count) values(%s,%s,%s) ON DUPLICATE KEY UPDATE count=count+%s”會報bug:not all arguments converted during string formatting
以上所述是小編給大家介紹的python executemany的使用及注意事項,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網(wǎng)網(wǎng)站的支持!
新聞熱點
疑難解答
圖片精選