我正在尝试在MySQL表中插入新行。当我随机生成ID时,我可以使用此代码,但是,当我更改表属性以使ID现在是自动递增字段时,该代码将不再起作用,因为该功能不再知道ID。
代码段:
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语句中生成的userID,而无需选择users表中的最后一列?
答案 0 :(得分:1)
您可以尝试使用MySQL提供的LAST_INSERT_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 documentation,您将发现LAST_INSERT_ID()
返回表中最后生成的自动增量值。只要您只为Python脚本使用单个连接,并且没有其他线程共享该连接,则上述方法应该有效。