mysql - 请建议我在 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()
解决方案
准备好的语句参数只能在 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():
推荐阅读
- python - 无法在 F3 运算符搜索中找到自定义 Blender 运算符(Blender 2.9)
- javascript - 在 Django 中将项目从一个列表动态移动到另一个列表
- java - 在 RecyclerView 中,在 OnBindViewHolder 方法中
- python - 加快 DataFrame .mask() 迭代
- node.js - npm install 错误并且无法更改根拥有文件的所有权
- sql - BigQuery 中的存储过程
- android - Android - 使状态栏图标颜色按背景自动更改
- embedded - 如何在 EFR32 上为 SI7021 图提供带有标志的 I2C 功能
- python - 理解值如何在 Python 中的合并排序中存储和传递的概念的问题
- pdf - 没有使用 Microsoft Graph API 调用将 Power Point 转换为 PDF