简体   繁体   中英

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. 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.

The way that I display the raw sql (which works most [but not all] of the time):

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. Some queries won't display, such as bulk inserts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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