How to write queries to file rather than executing them

Viewed 48
engine = sqlalchemy.engine.create_engine('mysql://py:123@localhost/py', echo=True)
con = engine.connect()
res = con.execute("insert into user set name = %s", 'A')

How do I write this query to a (.sql) file (or how do I assign it to a variable)? I'd rather not do all the escaping myself.

1 Answers

You can use literal_binds to produce an SQL statement with the values embedded:

import sqlalchemy as sa

# …

user = sa.Table("user", sa.MetaData(), autoload_with=engine)
user_insert = sa.insert(user).values(name="A")
compiled_text = str(
    user_insert.compile(compile_kwargs={"literal_binds": True})
)
print(compiled_text)
# INSERT INTO "user" (name) VALUES ('A')

However, be careful about using that with untrusted inputs as there is still the possibility of SQL injection issues.

Related