Python开发【笔记】:pymsyql 插入一条数据同时获取新插数据的自增id的两种方式
程序员文章站
2022-07-10 22:14:01
一、通过cursor.lastrowid 二、通过sql语句SELECT LAST_INSERT_ID() 表结构: ......
一、通过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}
表结构: