python中executemany的使用
1 conn = MySQLdb.connect(host = “localhost”, user = “root”, passwd = “password”, db = “myDB”, charset=’utf8′) 2 cursor = conn.cursor() 3 sql = “insert into myTable (created_day,name,count) values(%s,%s,%s) ON DUPLICATE KEY UPDATE count=count+values(count)” 4 args=[("2012-08-27","name1",100),("2012-08-27","name1",200),("2012-08-27","name2",300)] 5 try: 6 cursor.executemany(sql, args) 7 except Exception as e: 8 print0(“执行MySQL: %s 时出错:%s” % (sql, e)) 9 finally: 10 cursor.close() 11 conn.commit() 12 conn.close()
这里args是一个包含多个元组的数组,每个元组对应mysql当中的一条数据,注意这里的created_day对应的%s没有引号。这里推测executemany自己首先对sql语句进行正则匹配%s然后在此基础上,对字符串进行嵌入处理,如果这里%s加上引号的话,插入mysql当中会出现”0000-00-00″类型的错误日期。