Explore Courses Blog Tutorials Interview Questions
0 votes
in SQL by (20.3k points)

How do you execute raw SQL in SQLAlchemy?

I have a python web app that runs on flask and interfaces to the database through SQLAlchemy.

I need a way to run the raw SQL. The query involves multiple table joins along with Inline views.

I've tried:

connection = db.session.connection()

connection.execute( <sql here> )

But I keep getting gateway errors.

1 Answer

0 votes
by (40.7k points)

Try using as follows:

result = db.engine.execute("<sql here>")

Otherwise, you can use this 

from sqlalchemy import text

sql = text('select name from penguins')

result = db.engine.execute(sql)

names = [row[0] for row in result]

print names

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 12, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jul 27, 2019 in SQL by Soni Kumari (40.7k points)
0 votes
1 answer
asked Jul 2, 2020 in Python by Sudhir_1997 (55.6k points)
0 votes
1 answer
asked Jul 30, 2019 in Python by Eresh Kumar (45.3k points)

Browse Categories