gpt4 book ai didi

Python MySQLdb 执行表变量

转载 作者:行者123 更新时间:2023-11-29 15:18:05 24 4
gpt4 key购买 nike

我正在尝试使用变量作为表名。我收到错误“...在第 1 行的 ''myTable'' 附近我绝不能逃避这个权利。错误中的双“”似乎是一个线索,但我不明白。

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 字符串插值:

sql = "SELECT * FROM %s" % table
cursor.execute(sql)

当然,如果表名来自用户输入,您需要格外小心。为了缓解 SQL 注入(inject),请根据有效名称列表验证表名称。

关于Python MySQLdb 执行表变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59543291/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com