如何从db.engine.connect()获取inserted_primary_key.执行调用

gre*_*alm 7 python sqlalchemy flask

我正在使用:

CPython 2.7.3,
Flask==0.10.1
Flask-SQLAlchemy==0.16
psycopg2==2.5.1
and
postgresql-9.2
Run Code Online (Sandbox Code Playgroud)

试图通过alchemy插入调用来获取PK.

像这样得到引擎:

app = Flask(__name__)
app.config.from_envvar('SOME_VAR')
app.wsgi_app = ProxyFix(app.wsgi_app)  # Fix for old proxyes

db = SQLAlchemy(app)
Run Code Online (Sandbox Code Playgroud)

并在app中执行插入查询:

    from sqlalchemy import text, exc
    def query():
        return db.engine.connect().execute(text('''
        insert into test...'''), kw)
    rv = query()
Run Code Online (Sandbox Code Playgroud)

但是尝试访问inserted_primary_key属性,得到:

InvalidRequestError: Statement is not an insert() expression construct.
Run Code Online (Sandbox Code Playgroud)

如何在我的情况下启用implicit_returning,阅读文档没有帮助?

Paw*_*ech 5

您是否有任何理由进行文本查询而不是正常的 sqlalchemy insert() ?如果您使用 sqlalchemy,您可能会更容易将查询改写为:

from sqlalchemy import text, exc, insert

# in values you can put dictionary of keyvalue pairs
# key is the name of the column, value the value to insert
con = db.engine.connect()
ins = tablename.insert().values(users="frank")
res = con.execute(ins)
res.inserted_primary_key
[1] 
Run Code Online (Sandbox Code Playgroud)

这样 sqlalchemy 就会为您完成绑定。

  • 我喜欢原始 SQL,不想在 python 代码中第二次声明我的模式。我想要的只是在使用 db.engine.connect().execute('''raw sql insert here''' 插入后获取 PK id (7认同)

Mig*_*uel 5

您可以使用该RETURNING子句并自行处理:

INSERT INTO test (...) VALUES (...) RETURNING id
Run Code Online (Sandbox Code Playgroud)

然后,您可以检索ID,因为您通常从查询中检索值.

请注意,这适用于Postgres,但不适用于其他数据库引擎,如MySQL或sqlite.

我不认为在不使用ORM功能的情况下,在SQLAlchemy中有一种与数据库无关的方法.