使用 SQLAlchemy 从 MySQL 获取最后插入的值
我想返回 MySQL 中 auto_increment 字段的最后插入值。
我见过提到使用 session.flush()
添加记录然后检索 id 的示例。然而,这似乎总是返回 0。
我也看到过提到使用 session.refresh() 的示例,但这会引发以下错误:
InvalidRequestError: Could not refresh instance '<MyModel....>'
我的代码看起来像这样:
class Foo(Base):
__tablename__ = 'tblfoo'
__table_args__ = {'mysql_engine':'InnoDB'}
ModelID = Column(INTEGER(unsigned=True), default=0, primary_key=True, autoincrement=True)
ModelName = Column(Unicode(255), nullable=True, index=True)
ModelMemo = Column(Unicode(255), nullable=True)
f = Foo(ModelName='Bar', ModelMemo='Foo')
session.add(f)
session.flush()
此时,对象 f 已被推送到数据库,并已自动分配一个唯一的主键 id。但是,我似乎找不到一种方法来获取在某些附加操作中使用的值。我想执行以下操作:
my_new_id = f.ModelID
我知道我可以简单地执行另一个查询来根据其他参数查找 ModelID,但如果可能的话,我宁愿不这样做。
I want to return the last inserted value for an auto_increment field in MySQL.
I have seen examples that mention the use of session.flush()
to add the record and then retrieve the id. However that always seems to return 0.
I have also seen examples that mention the use of session.refresh() but that raises the following error:
InvalidRequestError: Could not refresh instance '<MyModel....>'
My code looks something like this:
class Foo(Base):
__tablename__ = 'tblfoo'
__table_args__ = {'mysql_engine':'InnoDB'}
ModelID = Column(INTEGER(unsigned=True), default=0, primary_key=True, autoincrement=True)
ModelName = Column(Unicode(255), nullable=True, index=True)
ModelMemo = Column(Unicode(255), nullable=True)
f = Foo(ModelName='Bar', ModelMemo='Foo')
session.add(f)
session.flush()
At this point, the object f has been pushed to the DB, and has been automatically assigned a unique primary key id. However, I can't seem to find a way to obtain the value to use in some additional operations. I would like to do the following:
my_new_id = f.ModelID
I know I could simply execute another query to lookup the ModelID based on other parameters but I would prefer not to if at all possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是您正在为自动增量设置
default
。因此,当它运行插入查询时,服务器的日志是所以输出是
0
这是默认值并且被传递,因为您正在为autoincrement
列设置默认值。如果我在没有
default
的情况下运行相同的代码,那么它会给出正确的输出。请尝试这个代码
The problem is you are setting
defaul
for the auto increment. So when it run the insert into query the log of server isSo the output is
0
which is the default value and which is passed because you are setting default value forautoincrement
column.If I run same code without
default
then it give the correct output.Please try this code
尝试使用
session.commit()
而不是session.flush()
。然后您可以使用f.ModelID
。Try using
session.commit()
instead ofsession.flush()
. You can then usef.ModelID
.不确定为什么标记的答案对您有用。但就我而言,这实际上并没有将行插入表中。我最终需要调用
commit()
。所以最后几行代码是:
Not sure why the flagged answer worked for you. But in my case, that does not actually insert the row into the table. I need to call
commit()
in the end.So the last few lines of code are: