如何使用 Python 获取 MySQL 数据库 INSERT 后生成的 ID?
数据是使用 INSERT 语句插入到 MySQL 表中的。在将数据插入表时,要么必须按照数据库中列定义的顺序提供数据,要么在使用 INSERT 语句时必须与数据一起提供列名。
要获取并打印最后插入行的 ID,可以使用 lastrowid。这是一个特殊的关键字,用于获取最后插入行的 ID。在使用此方法之前,需要考虑某些先决条件。
ID 列必须是表中的主键。
ID 列必须是自动增长的。
语法
cs.lastrowid
这里,cs 是游标对象。
使用 Python 中的 MySQL 获取表中插入行的 ID 的步骤
导入 MySQL 连接器
使用 connect() 方法建立与连接器的连接
使用 cursor() 方法创建游标对象
创建一个查询,将一行插入表中
使用 execute() 方法执行 SQL 查询
使用 lastrowid 获取插入行的 ID。
关闭连接
假设我们有以下名为“Students”的表。
+--------+---------+-----------+------------+ | id | Name | City | Marks | +--------+---------+-----------+------------+ | 1 | Karan | Amritsar | 95 | | 2 | Sahil | Amritsar | 93 | | 3 | Kriti | Batala | 88 | | 4 | Amit | Delhi | 90 | +--------+---------+-----------+------------+
示例
上面列中的 ID 列是主键并且是自动增长的。我们将向表中插入新行并获取最后插入行的 ID。
import mysql.connector db=mysql.connector.connect(host="your host", user="your username",password="your password",database="database_name") cursor=db.cursor() #insert a new row into the table query="INSERT INTO Students VALUES(5,“Priya”, “Amritsar”, 90)" cursor.execute(query) db.commit() #print the id of the inserted row print(cursor.lastrowid) db.close()
输出
5
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP