Retrieving Last Inserted ID after INSERT into MySQL Database with Python
When performing INSERT operations into a MySQL database using Python, obtaining the primary key of the newly inserted row can be crucial for further processing or referencing the data.本文提供了有關如何在Python檢索最後插入的ID的詳細說明和代碼示例。
使用Cursor.lastrowid 為當前的Cursor提供了最後插入Cursor的ID。要使用此方法,您需要:
導入mysql.connector #建立MySQL連接 連接= mysql.connector.connect(...) #創建光標對象 光標= Connection.Cursor() #執行插入語句 cursor.execute(“插入mytable(高度)值(%s)”,(高度)) #獲取最後一個插入的ID last_inserted_id = cursor.lastrowid使用connection.insert_id()
通過遵循這些方法,您可以使用python執行插入操作後,輕鬆地檢索最後一個插入的“ id”值。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3