Python MySQLdb执行表变量 [英] Python MySQLdb execute table variable
本文介绍了Python MySQLdb执行表变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用变量作为表名.我在第1行的"myTable"附近收到错误"..." 我一定不能逃避这项权利.错误中的双''似乎是一个线索,但我不明白.
I'm trying to use a variable for a table name. I get the error "... near ''myTable'' at line 1 I must not be escaping this right. The double '' in the error seems to be a clue, but I don't get it.
db = MySQLdb.connect("localhost","user","pw","database" )
table = "myTable"
def geno_order(db, table):
cursor = db.cursor() # prepare a cursor object using cursor() method
sql = "SELECT * FROM %s"
cursor.execute(sql, table)
results = cursor.fetchall()
推荐答案
您不能在execute
调用中为表名使用参数.您需要为此使用常规的Python字符串插值:
You can't use a parameter for the table name in the execute
call. You'll need to use normal Python string interpolation for that:
sql = "SELECT * FROM %s" % table
cursor.execute(sql)
自然,如果表名来自用户输入,则需要格外小心.为了减轻SQL注入,请对照有效名称列表验证表名称.
Naturally, you'll need to be extra careful if the table name is coming from user input. To mitigate SQL injection, validate the table name against a list of valid names.
这篇关于Python MySQLdb执行表变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文