一、通过cursor.lastrowid
import pymysql.cursors # Connect to the database connection = pymysql.connect(host='192.168.90.10',
port=3306,
user='remote',
password='123456',
db='Jefrey',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor,
autocommit = True) try: with connection.cursor() as cursor: # 增加
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
print(cursor.lastrowid)
finally:
connection.close() # 87
二、通过sql语句SELECT LAST_INSERT_ID()
import pymysql.cursors # Connect to the database connection = pymysql.connect(host='192.168.90.10',
port=3306,
user='remote',
password='123456',
db='Jefrey',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor,
autocommit = True) try: with connection.cursor() as cursor: # 增加
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
sql = 'SELECT LAST_INSERT_ID() AS id;'
cursor.execute(sql)
database = cursor.fetchone()
print(database)
finally:
connection.close() # {'id': 88}
表结构: