如何使用mysaldb插入到mysql表中,其中表名在python变量中? [英] how to insert to a mysql table using mysaldb, where the table name is in a python variable?
问题描述
我正在使用python-mysql db api将一些值插入到表名位于python变量中的表中.所以我写了下面的代码
I'm using python-mysql db api to insert some values to a table where the table name is in a python variable. So I wrote the below code
DB_CURSOR.execute("""INSERT INTO %s (name,created_by,state,description,docs,admin_email,date_created) VALUES(%s,%s,%s,%s,%s,%s,%s)""", (hosts_table, hostname, created_by, state, description, docroot, admin_email, date_created))
如您所见,表名称在hosts_table变量中.问题是mysqldb引用了表名,但出现了mysql错误.当我从字面上使用表名称时,它工作正常.我该如何解决?
As you see the table name is in the hosts_table variable. The problem is mysqldb quotes the table name and i get a mysql error. It works fine when I literally use the table name. How can I get around this?
推荐答案
DB_CURSOR.execute("""INSERT INTO %s
(name,created_by,state,description,docs,admin_email,date_created)
VALUES(%%s,%%s,%%s,%%s,%%s,%%s,%%s)""" % hosts_table,
(hostname, created_by, state, description, docroot, admin_email, date_created))
请注意,hosts_table变量是单个%符号,所有其他变量都是2 %%,因此在初始Python字符串插值中将忽略它们,然后将mysqldb部分更改为单个%.
Note that the hosts_table variable is a single % sign, and all the other variables are two %% so they are ignored in the initial Python string interpolation, then change to a single % for the mysqldb part.
在Python提示符中尝试此操作以了解我的意思:
Try this in the Python prompt to see what I mean:
>>> '%%s %s' % 'x'
'%s x'
这篇关于如何使用mysaldb插入到mysql表中,其中表名在python变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!