Python 获取以前生成的ID
我正试图在MySQL表中插入新行。当我随机生成ID时,这段代码正常工作,但是当我更改了表属性以便ID现在是自动递增字段时,代码不再工作,因为函数不再知道ID 代码段:Python 获取以前生成的ID,python,mysql,sql,Python,Mysql,Sql,我正试图在MySQL表中插入新行。当我随机生成ID时,这段代码正常工作,但是当我更改了表属性以便ID现在是自动递增字段时,代码不再工作,因为函数不再知道ID 代码段: def register(): #Insert Into Usertable userInsertSQL="""INSERT INTO users (username,password,stakeholder) VALUES (%s,%s,%s)""" mycursor.execute(userInsertSQL,(inputed
def register():
#Insert Into Usertable
userInsertSQL="""INSERT INTO users (username,password,stakeholder) VALUES (%s,%s,%s)"""
mycursor.execute(userInsertSQL,(inputedUsername.get(),inputedPassword.get(),inputedStakeholder.get()))
mydb.commit()
# Determine which table to place new user into
if inputedStakeholder.get() == "Employee":
employeeInsertSQL="""INSERT INTO employee (firstname,secondname,gender,userID) VALUES(%s,%s,%s,%s)"""
mycursor.execute(employeeInsertSQL,(inputedFirstName.get(),inputedSecondName.get(),inputedGender.get(),userID))
有没有一种方法可以在不选择用户表中的最后一列的情况下获得第一个Insert语句中生成的用户ID?您可以尝试使用MySQL提供的
last\u Insert\u ID()
函数:
if inputedStakeholder.get() == "Employee":
employeeInsertSQL = """INSERT INTO employee (firstname,secondname,gender,userID)
SELECT %s, %s, %s, LAST_INSERT_ID()"""
mycursor.execute(inputedFirstName.get(), inputedSecondName.get(),
inputedGender.get())
从MySQL中,您会发现
LAST\u INSERT\u ID()
返回表中最后生成的自动增量值。只要您的Python脚本只使用一个连接,并且没有其他线程共享该连接,上述方法就应该有效。我建议使用存储过程进行插入。然后可以将LAST\u INSERT\u ID()
传递回python代码。作为奖励,它可以避免SQL注入问题。