插入数据 INSERT

57.5 插入数据 INSERT

INSERT INTO 表(列1,列2) VALUES (值1,值2) — 插入一行。

INSERT INTO 表 VALUES (全列值...) — 省略列名时须按表结构顺序写全。

INSERT INTO 表(列) VALUES (v1),(v2),(v3) — 一次插入多行。

PyMySQL 用 %s 占位;executemany 批量插入;lastrowid 取自增 id。

INSERT 后必须 conn.commit() 才会写入磁盘。

💡 列有 DEFAULT 或允许 NULL 时,INSERT 可只写部分列。

单条、多条、批量插入

import pymysql

conn = pymysql.connect(host='127.0.0.1', user='root', password='root', database='py_demo', charset='utf8mb4')
try:
    with conn.cursor() as cur:
        # 单条
        cur.execute(
            'INSERT INTO students(name, score, class_name) VALUES (%s, %s, %s)',
            ('小新', 80, '一班')
        )
        print('新 id =', cur.lastrowid)
        # 一次写多行
        cur.execute(
            "INSERT INTO students(name, score) VALUES ('小周', 77), ('小吴', 83)"
        )
        # 批量(推荐)
        cur.executemany(
            'INSERT INTO students(name, score, class_name) VALUES (%s,%s,%s)',
            [('小郑', 90, '三班'), ('小冯', 66, '三班')]
        )
    conn.commit()
finally:
    conn.close()