首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取之前生产的ID

问获取之前生产的ID
EN

Stack Overflow用户
提问于 2019-09-08 00:21:10
回答 1查看 16关注 0票数 0

我正尝试在我的MySQL表中插入一个新行。当我随机生成IDs时,我让这段代码工作,但是,当我更改表属性,使IDs现在是自动增量字段时,代码不再工作,因为Ids不再为函数所知。

代码片段:

代码语言:javascript
复制
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))

有没有一种方法可以在不选择users表中的最后一列的情况下获得第一个Insert语句中生成的userID?

EN

回答 1

Stack Overflow用户

发布于 2019-09-08 00:27:14

您可以尝试使用MySQL提供的LAST_INSERT_ID()函数:

代码语言:javascript
复制
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脚本使用单个连接,并且没有其他线程共享该连接,则上述方法应该有效。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57835491

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档