简体   繁体   English

如何从sqlalchemy中的session.add()获取原始sql?

[英]How to get raw sql from session.add() in sqlalchemy?

是从insert获取原始sql的答案,我想知道如果我使用session.add() ,我是否可以获得原始sql:

session.add(ormclass).compile()

If you want SQLAlchemy to log the actual raw SQL queries you can always set echo=True on the create_engine method. 如果希望SQLAlchemy记录实际的原始SQL查询,则始终可以在create_engine方法上设置echo=True I know this seems rudimentary but it's the easiest way to see executed queries. 我知道这似乎很简陋,但这是查看已执行查询的最简单方法。

engine = create_engine("postgresql://localhost/dbname", echo=True)

My temporal solution to this is that when an error happens, there will be an exception and in this exception there are the parameters and statement. 我对此的时间解决方案是,当发生错误时,会出现异常,并且在此异常中有参数和语句。

except Exception as inst:
    print(inst.statement % inst.params)

But the problem still exists because I cannot get the statement and parameters if there are no exceptions. 但问题仍然存在,因为如果没有例外,我无法获得语句和参数。 In addition, there are no quotation marks for strings in the print so the string cannot be executed in mysql directly. 另外,打印中的字符串没有引号,因此字符串不能直接在mysql中执行。

The way that I display the raw sql (which works most [but not all] of the time): 我显示原始sql的方式(最常用[但不是全部]):

query = [my query that I created]
from sqlalchemy.dialects import mysql
str_query = query.compile(dialect=mysql.dialect(), compile_kwargs={"literal_binds": True})

Then I can just print the sql_query statement and it will show me the query with arguments. 然后我可以打印sql_query语句,它将显示带参数的查询。 Some queries won't display, such as bulk inserts. 某些查询不会显示,例如批量插入。

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

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