You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python执行SQL查询时如何在查询字符串中使用变量传入表名

问题说明

需求为查询world数据库中用户指定表的全部数据,硬编码查询city表的代码可正常输出结果,代码如下:

from sqlite3 import connect
import mysql.connector 
mydb=mysql.connector.connect(host="localhost",user="root",password="",database='world')
mycursor=mydb.cursor()
mycursor.execute("select * from city")
for i in mycursor:
    print(i)

尝试将硬编码的city替换为用户输入的字符串变量时,直接在SQL语句中写入table_name会触发报错,提示world.table_name不存在,错误实现代码如下:

table_name=str(input("enter table name:"))
mycursor=mydb.cursor()
mycursor.execute("select * from table_name")
for i in mycursor:
    print(i)

报错核心原因:SQL语句中直接书写table_name时,数据库会将其识别为固定命名为table_name的表,不会解析为外部传入的Python变量值。需要注意:MySQL标准参数化查询仅支持对查询值类型的参数做占位替换,不支持用占位符代表表名、字段名这类结构类标识符,未做校验直接拼接用户输入会存在SQL注入风险。

正确实现方法
  • 第一步做表名合法性校验:先查询当前库下所有存在的表,校验用户输入的表名在合法范围内,既可以避免无效表名报错,也能阻断SQL注入风险
  • 校验通过后,通过字符串格式化将合法表名拼接进SQL语句执行即可,拼接时用反引号包裹表名,避免表名与SQL关键字重名引发语法错误

完整代码如下:

import mysql.connector 

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    password="",
    database='world'
)
mycursor = mydb.cursor()

table_name = input("enter table name:").strip()

# 校验输入表名是否存在
mycursor.execute("SHOW TABLES")
valid_tables = [t[0] for t in mycursor.fetchall()]
if table_name not in valid_tables:
    print(f"错误:数据库world中不存在表{table_name}")
    exit()

# 执行查询
mycursor.execute(f"SELECT * FROM `{table_name}`")
for row in mycursor:
    print(row)

内容的提问来源于stack exchange,提问作者def init

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.31 08:30:47