Python和MySQLdb:替换表会导致语法错误 [英] Python and MySQLdb: substitution of table resulting in syntax error
问题描述
我需要不时动态地更改表和变量,所以我编写了这样的python方法:
I need to dynamically change tables and variables from time to time, so I wrote a python method like this:
selectQ ="""SELECT * FROM %s WHERE %s = %s;"""
self.db.execute(selectQ,(self.table,self.columnSpecName,idKey,))
return self.db.store_result()
但是,这将导致语法错误异常.我尝试对其进行调试,因此我在方法中打印了变量,然后手动将其填充,并且可以正常工作.所以我不确定我在做什么错了吗?
However this results in a syntax error exception. I tried debugging it so I printed the variables in the method and filled them in manually, and that worked. So I am not sure what I am doing wrong ?
是因为我尝试使用表的替代品吗?
Is it because I try to use a substitute for a table ?
我也该如何调试mysqldb以便将替换查询打印为字符串?
Also how do I debug mysqldb so it prints the substituted query as a string ?
推荐答案
DB API中的参数替换仅适用于值-不适用于表或字段.您将需要使用普通的字符串替换:
Parameter substitution in the DB API is only for values - not tables or fields. You'll need to use normal string substitution for those:
selectQ ="""SELECT * FROM %s WHERE %s = %%s;""" % (self.table,self.columnSpecName)
self.db.execute(selectQ,(idKey,))
return self.db.store_result()
请注意,值占位符有一个双精度%
-这样就可以在初始字符串替换中将其保留.
Note that the value placeholder has a double %
- this is so that it's left alone by the initial string substitution.
这篇关于Python和MySQLdb:替换表会导致语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!