簡體   English   中英

使用 Python 插入 MySQL 數據庫后如何獲取“id”?

[英]How do I get the “id” after INSERT into MySQL database with Python?

我執行 INSERT INTO 語句

cursor.execute("INSERT INTO mytable(height) VALUES(%s)",(height))

我想獲得主鍵。

我的表有 2 列:

id      primary, auto increment
height  this is the other column.

我剛剛插入后如何獲得“id”?

使用cursor.lastrowid獲取插入到游標對象的最后一行 ID,或使用connection.insert_id()獲取該連接上最后一次插入的 ID。

此外, cursor.lastrowid (MySQLdb 支持的 dbapi/PEP249 擴展):

>>> import MySQLdb
>>> connection = MySQLdb.connect(user='root')
>>> cursor = connection.cursor()
>>> cursor.execute('INSERT INTO sometable VALUES (...)')
1L
>>> connection.insert_id()
3L
>>> cursor.lastrowid
3L
>>> cursor.execute('SELECT last_insert_id()')
1L
>>> cursor.fetchone()
(3L,)
>>> cursor.execute('select @@identity')
1L
>>> cursor.fetchone()
(3L,)

cursor.lastrowidconnection.insert_id()便宜一些,比另一個到 MySQL 的往返便宜得多。

Python DBAPI 規范還為游標對象定義了“lastrowid”屬性,因此...

id = cursor.lastrowid

...也應該可以工作,而且它顯然是基於每個連接的。

SELECT @@IDENTITY AS 'Identity';

或者

SELECT last_insert_id();

這可能只是 Python 中 PyMySql 的一個要求,但我發現我必須命名我想要 ID 的確切表:

在:

cnx = pymysql.connect(host='host',
                            database='db',
                            user='user',
                            password='pass')
cursor = cnx.cursor()
update_batch = """insert into batch set type = "%s" , records = %i, started = NOW(); """
second_query = (update_batch % ( "Batch 1", 22  ))
cursor.execute(second_query)
cnx.commit()
batch_id = cursor.execute('select last_insert_id() from batch')
cursor.close()

batch_id

輸出:5
...或任何正確的 Batch_ID 值實際上是

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM