Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert sqlalchemy core statements to raw SQL without a connection?

Tags:

sqlalchemy

I have a script that uses sqlalchemy core, but I unfortunately need to rewrite it to use raw sql instead. Is it possible to translate my sqla insert/etc… statements into a specfic dialect (oracle here) without an explicit engine ?

Essentially, being able to use a non default engine for str(some_sqla_core_expression) ?

like image 384
David Cournapeau Avatar asked Feb 10 '12 15:02

David Cournapeau


People also ask

How do I run a raw SQL query in SQLAlchemy?

Import necessary functions from the SQLAlchemy package. Establish connection with the PostgreSQL database using create_engine() function as shown below, create a table called books with columns book_id and book_price. Insert record into the tables using insert() and values() function as shown.

What is SQLAlchemy core?

SQLAlchemy is a library used to interact with a wide variety of databases. It enables you to create data models and queries in a manner that feels like normal Python classes and statements.


1 Answers

any expression becomes a string like this (basically stmt.compile(dialect=dialect)):

from sqlalchemy.sql import column, table, select
from sqlalchemy.dialects import oracle

dialect = oracle.dialect()
table = table('sometable', column('id'), column('data'))
stmt = select([table]).where(table.c.id==5).where(table.c.data=='foo')
raw_sql = unicode(stmt.compile(dialect=dialect))
print raw_sql

There's actually an example of this in the SQL tutorial at the moment here: http://docs.sqlalchemy.org/en/latest/core/tutorial.html#using-joins

like image 143
zzzeek Avatar answered Nov 24 '22 01:11

zzzeek