首页 > 解决方案 > 请建议我在 sql 查询中使用 python 变量的正确方法

问题描述

我想在代码下面运行,但我收到语法错误。

cur.execute("USE Test") # select the database
cur.execute("SHOW TABLES")

for (table_name,) in cur:
    print(table_name)
    trunc_table="truncate table %s"
    cur.execute(trunc_table, table_name)
    con.commit()

标签: mysqlpython-2.7

解决方案


准备好的语句参数只能在 SQL 允许表达式的地方使用。表名不是表达式,它们必须是查询中的文字。您可以使用字符串格式替换字符串。

trunc_table = "truncate table %s" % table_name
cur.execute(trunc_table)

另外,我认为在循环第一个查询的结果时,您需要使用不同的游标来执行第二个查询。所以在循环之前,做:

cur2 = connection.cursor()
cur2.execute("USE Test")

然后使用

cur2.execute(trunc_table)

在循环。另一种选择是先cur.fetchall()获取所有行,然后您可以重用游标。

for (table_name,) in cur.fetchall():

推荐阅读