本文介绍了Python中的MySQL动态查询语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试完成以下任务:
I am trying to accomplish something like the following:
cursor = db.cursor()
cursor.execute('INSERT INTO media_files (%s, %s, %s, %s ... ) VALUES (%s, %s, %s, %s, ...)', (fieldlist, valuelist))
cursor.commit()
我有2个列表,字段列表和值列表,每个列表包含相同数量的项目.生成动态MySQL查询语句的最佳方法是什么?将列存储在字段列表中,将值存储在值列表中?
I have 2 lists, fieldlist and valuelist which each contain the same number of items. What is the best way to generate a dynamic MySQL query statement where the collumns are stored in fieldlist and the values are stored in valuelist?
推荐答案
cursor.execute('INSERT INTO media_files (%s) VALUES (%%s, %%s, %%s, %%s, ...)' % ','.join(fieldlist), valuelist)
更清晰地说:
sql = 'INSERT INTO media_files (%s) VALUES (%%s, %%s, %%s, %%s, ...)' % ','.join(fieldlist)
cursor.execute(sql, valuelist)
这篇关于Python中的MySQL动态查询语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!