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

Python中将列表元素转为SQL查询字符串遇问题,求正确实现

解决Python列表转SQL查询语句的问题

原代码的问题

  • 循环里错误使用str(A),会把整个列表转成字符串,而非当前遍历的单个元素i
  • 字符串拼接语法错误,未用引号包裹Python代码中的SQL字符串
  • 直接拼接含单引号的元素会导致SQL语法错误,还存在SQL注入风险

正确实现方式

方式一:生成单个元素对应的查询语句(遍历列表)

如果要为列表中每个元素生成单独的查询语句,可参考以下代码:

A = ["machine's code", "max's code"]
for item in A:
    # 用双引号包裹SQL字符串,避免和元素内的单引号冲突
    query = f"Select * from table where name=\"{item}\""
    print(query)

运行后输出:

Select * from table where name="machine's code"
Select * from table where name="max's code"

方式二:使用参数化查询(推荐,规避SQL注入)

直接拼接字符串存在安全风险,更规范的做法是借助数据库驱动的参数化查询,以MySQL为例:

import mysql.connector

A = ["machine's code", "max's code"]
db = mysql.connector.connect(host="localhost", user="your_user", password="your_pass", database="your_db")
cursor = db.cursor()

for item in A:
    # %s为参数占位符,数据库驱动会自动处理引号转义
    query = "Select * from table where name=%s"
    cursor.execute(query, (item,))
    # 获取查询结果
    result = cursor.fetchall()
    print(result)

cursor.close()
db.close()

补充:生成IN条件的批量查询

如果需要一次性查询所有匹配元素,可生成IN条件的语句:

A = ["machine's code", "max's code"]
# 生成对应数量的参数占位符
placeholders = ", ".join(['%s'] * len(A))
query = f"Select * from table where name IN ({placeholders})"
# 执行时传入整个列表作为参数
cursor.execute(query, A)

内容的提问来源于stack exchange,提问作者Ratna Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 16:40:54