Python开发【笔记】:pymsyql 插入一条数据同时获取新插数据的自增id的两种方式
程序员文章站
2022-04-04 17:04:46
一、通过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}
表结构:
上一篇: HTC U11 Eyes手机曝光 国行已经得到3C认证
下一篇: NIO-直接内存