Including DB function calls in python MySQLdb executemany()

偶尔善良 提交于 2019-12-06 12:45:20

The method below is far from ideal, but, unfortunately, it is the only way I know.

The idea is to manually construct the SQL, using connection.literal to escape the arguments for you:

cursor=connection.cursor()
args=[(1,'foo'),(2,'bar')]
sql=('INSERT INTO `foo` (`fooid`,`data`,`time_added`) VALUES '
     +','.join(
         ['(%s,%s,NOW())'%connection.literal(arg)
          for arg in args]))
cursor.execute(sql)

This looks horrible, and may make your skin crawl, but if you look under the hood (in /usr/lib/pymodules/python2.6/MySQLdb/cursors.py) at what MySQLdb is doing in cursors.executemany, I think this is along the same lines as what that function is doing, minus the mixup due the regex cursors.insert_values not correctly parsing the nested parentheses. (eek!)


I've just installed oursql, an alternative to MySQLdb, and am happy to report that

sql='INSERT INTO `foo` (`fooid`,`data`,`time_added`) VALUES (?,?,NOW())'
cursor.executemany(sql,args)

works as expected with oursql.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!