使用 Python 连接 MySQL 并写入数据

在使用 MySQL 数据库时,我们常常需要往数据表中插入新记录。本文将示例如何用 Python 的 mysql-connector 驱动程序来进行单条或多条数据的插入,以及获取自增主键 ID 的方法。

1. 插入单条记录

以下示例在名为 customers 的表中插入一条数据:

import mysql.connector

mydb = mysql.connector.connect(
    host="localhost",
    user="yourusername",
    password="yourpassword",
    database="mydatabase"
)

mycursor = mydb.cursor()

sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")

mycursor.execute(sql, val)
mydb.commit()  # 提交变更,若不提交则不生效

print(mycursor.rowcount, "record inserted.")

注意:必须调用mydb.commit()才能真正写入数据库,否则执行完execute后不会保存。

2. 插入多条记录(批量插入)

想一次插入多行,可以使用 executemany() 方法。第二个参数是包含多行数据的列表,每行数据以元组形式表示:

sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = [
    ("Peter", "Lowstreet 4"),
    ("Amy", "Apple st 652"),
    ("Hannah", "Mountain 21"),
    # 可继续添加更多
]

mycursor.executemany(sql, val)
mydb.commit()

print(mycursor.rowcount, "was inserted.")

这能大大简化批量写入的代码,提高插入效率。

3. 获取最后插入的自增 ID

如果表里有自增主键(AUTO_INCREMENT),我们可以在插入数据后通过 mycursor.lastrowid 获取最后一次插入的 ID:

sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("Michelle", "Blue Village")
mycursor.execute(sql, val)
mydb.commit()

print("1 record inserted, ID:", mycursor.lastrowid)

当一次插入多条记录时,lastrowid只会返回其中最后一条的自增 ID。

建议与提醒

  • 确保表结构中已包含对应的列 (如 nameaddress),且类型匹配。
  • 使用带参数的 SQL (如 %s) 以防止 SQL 注入并增强可读性。
  • 操作数据库前确认账号权限,否则可能导致插入失败。

通过以上示例,你可以轻松完成 Python 与 MySQL 的数据写入操作,实现单条或多条记录的插入,并在需要时获取自增 ID。