Python MySQLdb execute table variable [duplicate]

百般思念 提交于 2019-12-17 07:49:11

问题


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()

回答1:


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)

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.



来源:https://stackoverflow.com/questions/15255694/python-mysqldb-execute-table-variable

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