简体   繁体   English

使用SQLAlchemy从MySQL获取最后插入的值

[英]Get last inserted value from MySQL using SQLAlchemy

I've just run across a fairly vexing problem, and after testing I have found that NONE of the available answers are sufficient. 我遇到了一个相当棘手的问题,经过测试后我发现没有可用的答案就足够了。

I have seen various suggestions but none seem to be able to return the last inserted value for an auto_increment field in MySQL. 我已经看到了各种建议,但似乎没有人能够返回MySQL中auto_increment字段的最后插入值。

I have seen examples that mention the use of session.flush() to add the record and then retrieve the id. 我看过一些例子,提到使用session.flush()来添加记录然后检索id。 However that always seems to return 0. 然而,似乎总是返回0。

I have also seen examples that mention the use of session.refresh() but that raises the following error: InvalidRequestError: Could not refresh instance '' 我也看到过提及session.refresh()使用的例子,但会引发以下错误:InvalidRequestError:无法刷新实例''

What I'm trying to do seems insanely simple but I can't seem to figure out the secret. 我想做的事似乎非常简单,但我似乎无法弄明白这个秘密。

I'm using the declarative approach. 我正在使用声明式方法。

So, 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. 此时,对象f已被推送到DB,并且已自动分配了唯一的主键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 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. 我知道我可以简单地执行另一个查询来根据其他参数查找ModelID,但我不愿意,如果可能的话。

I would much appreciate any insight into a solution to this problem. 我非常感谢任何有关此问题的解决方案的见解。

Thanks for the help in advance. 我在这里先向您的帮助表示感谢。

The problem is you are setting defaul for the auto increment. 问题是你正在为自动增量设置defaul值。 So when it run the insert into query the log of server is 所以当它运行插入查询服务器的日志时

2011-12-21 13:44:26,561 INFO sqlalchemy.engine.base.Engine.0x...1150 INSERT INTO tblfoo (`ModelID`, `ModelName`, `ModelMemo`) VALUES (%s, %s, %s)
2011-12-21 13:44:26,561 INFO sqlalchemy.engine.base.Engine.0x...1150 (0, 'Bar', 'Foo')
ID : 0

So the output is 0 which is the default value and which is passed because you are setting default value for autoincrement column. 因此输出为0 ,这是默认值,因为您要为autoincrement列设置默认值,所以它会被传递。

If I run same code without default then it give the correct output. 如果我没有default运行相同的代码,那么它会给出正确的输出。

Please try this code 请试试这段代码

from sqlalchemy import create_engine
engine = create_engine('mysql://test:test@localhost/test1', echo=True)

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)

session = Session()

from sqlalchemy import Column, Integer, Unicode

class Foo(Base):
    __tablename__ = 'tblfoo'
    __table_args__ = {'mysql_engine':'InnoDB'}

    ModelID = Column(Integer, primary_key=True, autoincrement=True)
    ModelName = Column(Unicode(255), nullable=True, index=True)
    ModelMemo = Column(Unicode(255), nullable=True)

Base.metadata.create_all(engine)

f = Foo(ModelName='Bar', ModelMemo='Foo')
session.add(f)
session.flush()

print "ID :", f.ModelID

Try using session.commit() instead of session.flush() . 尝试使用session.commit()而不是session.flush() You can then use f.ModelID . 然后,您可以使用f.ModelID

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. 我最后需要调用commit()

So the last few lines of code are: 所以最后几行代码是:

f = Foo(ModelName='Bar', ModelMemo='Foo')
session.add(f)
session.flush()

print "ID:", f.ModelID

session.commit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM