如何使用 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
廣告