插入数据

56.4 插入数据

INSERT INTO 表(列1,列2) VALUES (?,?) 用 ? 占位符传参,防止 SQL 注入。

executemany 批量插入多条,比循环 execute 更高效。

lastrowid 获取刚插入的自增 id。

单条与批量插入

import sqlite3

rows = [('小明', 95), ('小红', 88), ('小刚', 72)]
with sqlite3.connect('school.db') as conn:
    cur = conn.cursor()
    cur.executemany(
        'INSERT INTO students(name, score) VALUES (?, ?)',
        rows
    )
    print('最后插入 id =', cur.lastrowid)
print('共插入', len(rows), '条')

⚠️ 常见错误与正确对比

❌ 错误写法
cur.execute(f"INSERT INTO students(name) VALUES ('{name}')")
✅ 正确写法
cur.execute('INSERT INTO students(name) VALUES (?)', (name,))

📌 用户输入拼进 SQL 可能被注入攻击,必须用 ? 占位符。