[Pymysql] Get the value of the auto-incremented field submitted last time

Code

import pymysql

conn=pymysql.connect(
    host="127.0.0.1",
    user="root",
    password="123456",
    database="test",
    charset="utf8"
)
# 拿到游标对象,游标是给mysql提交命令的接口
cursor=conn.cursor()
# 执行sql语句
# 增、删、改
sql= 'insert into docfield(text,inindustry) values(%s,%s);'
# 查
sql_search='select * from docfield'

# 把sql语句传给游标执行
rows=cursor.execute(sql, ("123","99"))
print(rows)
print(cursor.lastrowid)
conn.commit()
cursor.execute(sql_search)
rs=cursor.fetchall()
print(rs)
print(cursor.lastrowid)	#返回None
# 执行完sql语句要关闭游标和mysql连接
cursor.close()
conn.close()

Key part description

  1. Cursor is a cursor. Only when the cursor performs addition, deletion and modification operations, can the value of the auto-increment field of the last operation be obtained through cursor.lastrowid.
  2. When the cursor performs a search operation, cursor.lastrowid can only get None, which is empty.
  3. When the cursor does not execute any sql and directly obtains the lastrowid, an exception will be thrown and an error will be reported!

Guess you like

Origin blog.csdn.net/kz_java/article/details/114898723