python executemany的使用及注意事項
使用executemany對數(shù)據(jù)進(jìn)行批量插入的話,要注意一下事項:
#coding:utf8 conn = 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ù)組,每個元組對應(yīng)mysql當(dāng)中的一條數(shù)據(jù),注意這里的created_day對應(yīng)的%s沒有引號。這里推測executemany自己首先對sql語句進(jìn)行正則匹配%s然后在此基礎(chǔ)上,對字符串進(jìn)行嵌入處理,如果這里%s加上引號的話,插入mysql當(dāng)中會出現(xiàn)”0000-00-00″類型的錯誤日期。
如果一次性要插入很多條數(shù)據(jù)的話,在這里強(qiáng)烈 推薦使用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的使用及注意事項,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
python中的?sorted()函數(shù)和sort()方法區(qū)別
這篇文章主要介紹了python中的?sorted()函數(shù)和sort()方法,首先看sort()方法,sort方法只能對列表進(jìn)行操作,而sorted可用于所有的可迭代對象。具體內(nèi)容需要的小伙伴可以參考下面章節(jié)2022-02-02