Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
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.4k 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.4k points)
0 votes
1 answer
asked Jul 2, 2020 in Python by Sudhir_1997 (55.5k points)
0 votes
1 answer
asked Jul 30, 2019 in Python by Eresh Kumar (45.3k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94k users

Browse Categories

...