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

如何在Python 3中遍历数组批量生成SQL INSERT语句?

多数组遍历生成SQL INSERT语句的实现方案

核心思路

使用Python的zip()函数将三个列表按索引配对,一次性遍历每组对应的种族、职业和阵营数据,代入SQL模板生成对应的INSERT语句。

修正后的完整代码

raceValues = [
    "Human",
    "Elf",
    "Orc"
]

classValues = [
    "Fighter",
    "Mage",
    "Cleric"
]

alignmentValues = [
    "Good",
    "Neutral",
    "Evil"
]

# 同时遍历三个列表的对应元素
for race, cls, alignment in zip(raceValues, classValues, alignmentValues):
    # 注意:class是SQL关键字,需用反引号(MySQL)转义,其他数据库可替换为对应语法(如SQL Server用[])
    insert_command = f"INSERT INTO game.Characters(race, `class`, alignment) VALUES ('{race}', '{cls}', '{alignment}');"
    print(insert_command)

代码说明

  1. zip()函数的作用:将三个列表中索引位置相同的元素打包成元组,循环时每次取出一组(race, class, alignment)数据,正好对应一条INSERT语句的字段值。
  2. SQL关键字转义:class是SQL保留关键字,作为字段名使用时需要用反引号(MySQL)包裹,避免语法错误。
  3. 字符串格式化:使用Python 3.6+支持的f-string,语法简洁直观,直接将变量代入模板。

安全优化(避免SQL注入)

如果你的数据来自非可信来源,建议使用参数化查询代替直接字符串拼接,示例如下(以SQLite为例):

import sqlite3

# 建立数据库连接
conn = sqlite3.connect("your_database.db")
cursor = conn.cursor()

# 参数化INSERT模板
insert_template = "INSERT INTO game.Characters(race, `class`, alignment) VALUES (?, ?, ?);"

# 批量插入数据
for race, cls, alignment in zip(raceValues, classValues, alignmentValues):
    cursor.execute(insert_template, (race, cls, alignment))

# 提交事务并关闭连接
conn.commit()
conn.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 23:25:17