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

Posted in :

滿實用的,取流水號(identity)的方法。


Also, cursor.lastrowid (a dbapi/PEP249 extension supported by MySQLdb):

>>> 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,)

如果 python3 無法使用 MySQLdb 參考這篇:Python 連 mysql
http://stackoverflow.max-everyday.com/2017/09/python-mysql/

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *