SQLAlchemy 2.0:

with engine.connect() as connection:
    result = connection.execute(text('SELECT * FROM your_table'))
    # do something with the result..

SQLAlchemy 1.x:

from sqlalchemy import text

sql = text('select name from penguins')
result = db.engine.execute(sql)
names = [row[0] for row in result]
print names

Note that db.engine.execute() is "connectionless", which is deprecated in SQLAlchemy 2.0.

Answer from Miguel Grinberg on Stack Overflow
🌐
Atlassian
atlassian.com › data › notebook › how-to-execute-raw-sql-in-sqlalchemy
How to Execute Raw SQL in SQLAlchemy | Atlassian
The most readable way to use text is to import the module, then after connecting to the engine, define the text SQL statement string before using .execute to run it: 1from sqlalchemy.sql import text 2with engine.connect() as con: 3 4 data = ( { "id": 1, "title": "The Hobbit", "primary_author": ...
Top answer
1 of 10
439

SQLAlchemy 2.0:

with engine.connect() as connection:
    result = connection.execute(text('SELECT * FROM your_table'))
    # do something with the result..

SQLAlchemy 1.x:

from sqlalchemy import text

sql = text('select name from penguins')
result = db.engine.execute(sql)
names = [row[0] for row in result]
print names

Note that db.engine.execute() is "connectionless", which is deprecated in SQLAlchemy 2.0.

2 of 10
293

SQL Alchemy session objects have their own execute method:

result = db.session.execute('SELECT * FROM my_table WHERE my_column = :val', {'val': 5})

All your application queries should be going through a session object, whether they're raw SQL or not. This ensures that the queries are properly managed by a transaction, which allows multiple queries in the same request to be committed or rolled back as a single unit. Going outside the transaction using the engine or the connection puts you at much greater risk of subtle, possibly hard to detect bugs that can leave you with corrupted data. Each request should be associated with only one transaction, and using db.session will ensure this is the case for your application.

Also take note that execute is designed for parameterized queries. Use parameters, like :val in the example, for any inputs to the query to protect yourself from SQL injection attacks. You can provide the value for these parameters by passing a dict as the second argument, where each key is the name of the parameter as it appears in the query. The exact syntax of the parameter itself may be different depending on your database, but all of the major relational databases support them in some form.

Assuming it's a SELECT query, this will return an iterable of RowProxy objects.

You can access individual columns with a variety of techniques:

for r in result:
    print(r[0]) # Access by positional index
    print(r['my_column']) # Access by column name as a string
    r_dict = dict(r.items()) # convert to dict keyed by column names

Personally, I prefer to convert the results into namedtuples:

from collections import namedtuple

Record = namedtuple('Record', result.keys())
records = [Record(*r) for r in result.fetchall()]
for r in records:
    print(r.my_column)
    print(r)

If you're not using the Flask-SQLAlchemy extension, you can still easily use a session:

import sqlalchemy
from sqlalchemy.orm import sessionmaker, scoped_session

engine = sqlalchemy.create_engine('my connection string')
Session = scoped_session(sessionmaker(bind=engine))

s = Session()
result = s.execute('SELECT * FROM my_table WHERE my_column = :val', {'val': 5})
🌐
SQLAlchemy
docs.sqlalchemy.org › en › 14 › core › tutorial.html
SQL Expression Language Tutorial (1.x API) — SQLAlchemy 1.4 Documentation
That’s why SQLAlchemy lets you just use strings, for those cases when the SQL is already known and there isn’t a strong need for the statement to support dynamic features. The text() construct is used to compose a textual statement that is passed to the database mostly unchanged. Below, ...
🌐
SQLAlchemy
docs.sqlalchemy.org › en › 20 › core › connections.html
Working with Engines and Connections — SQLAlchemy 2.0 Documentation
Our example above illustrated the execution of a textual SQL string, which should be invoked by using the text() construct to indicate that we’d like to use textual SQL. The Connection.execute() method can of course accommodate more than that; see Working with Data in the SQLAlchemy Unified ...
🌐
TutorialsPoint
tutorialspoint.com › sqlalchemy › sqlalchemy_core_using_textual_sql.htm
SQLAlchemy Core - Using Textual SQL
from sqlalchemy import text t = text("SELECT * FROM students") result = connection.execute(t)
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-execute-raw-sql-in-sqlalchemy
How to Execute Raw SQL in SQLAlchemy - GeeksforGeeks
February 28, 2022 - from sqlalchemy import text text("YOUR SQL QUERY") Pass the SQL query to the execute() function and get all the results using fetchall() function. Use a for loop to iterate through the results.
🌐
ZetCode
zetcode.com › db › sqlalchemy › rawsql
Raw SQL in SQLAlchemy
#!/usr/bin/python # -*- coding: utf-8 -*- from sqlalchemy import create_engine from sqlalchemy.sql import text eng = create_engine('sqlite:///:memory:') with eng.connect() as con: con.execute(text('''CREATE TABLE Cars(Id INTEGER PRIMARY KEY, Name TEXT, Price INTEGER)''')) rs = con.execute(text('SELECT * FROM Cars')) print rs.keys()
Find elsewhere
🌐
Sentry
sentry.io › sentry answers › flask › execute raw sql in flask-sqlalchemy application
Execute raw SQL in Flask-SQLAlchemy application | Sentry
March 15, 2024 - from sqlalchemy import text query = text("SELECT name, price FROM products") result = db.engine.execute(query)
🌐
Soogoonsoogoonpythonists
soogoonsoogoonpythonists.github.io › sqlalchemy-for-pythonist › en › tutorial › 3. Executing Transactions and Queries.html
Executing Transactions and Queries | SQLAlchemy for Python Developers
You can connect to the database and execute a query as follows. >>> from sqlalchemy import text >>> with engine.connect() as conn: ... result = conn.execute(text("select 'hello world'")) ... print(result.all()) [('hello world',)] Obtain a Connection (opens new window) object through ...
Top answer
1 of 3
133

The tutorial gives a pretty good example for this:

>>> from sqlalchemy.sql import text
>>> s = text(
...     "SELECT users.fullname || ', ' || addresses.email_address AS title "
...         "FROM users, addresses "
...         "WHERE users.id = addresses.user_id "
...         "AND users.name BETWEEN :x AND :y "
...         "AND (addresses.email_address LIKE :e1 "
...             "OR addresses.email_address LIKE :e2)")
SQL>>> conn.execute(s, {"x": "m", "y": "z", "e1": "%@aol.com", "e2": "%@msn.com"}).fetchall() 
[(u'Wendy Williams, [email protected]',)]

First, take your SQL string and pass it to sqalchemy.sql.text(). This isn't necessary, but probably a good idea...

The advantages text() provides over a plain string are backend-neutral support for bind parameters, per-statement execution options, as well as bind parameter and result-column typing behavior, allowing SQLAlchemy type constructs to play a role when executing a statement that is specified literally.

Note that even if you didn't use text(), you should NEVER just use sql.format(...). This leads to greater risk of SQL injection attacks.

Next, you can specify the actual arguments using keyword parameters to the execute() function you've already been using.

Now, in your example, you have a function that wraps the execute functionality. So, if you want to use this for multiple queries, you'll need to make the parameters able to receive your arguments. You could do this pretty simple as a dictionary:

def _sql_to_data(sql, values):
    ...
    conn.execute(sql, values)

values would be a dictionary.You could then use your function like this...

sql = 'SELECT ...'
data = { 'user_id' : 3 }
results = _sql_to_data(sql, data)

Using keywords as your parameters is just one way of specifying the arguments to the execute() function. You can read the documentation for that function for a few different ways.

2 of 3
17

This is the latest way to bind params for session execute

stmt = text("SELECT * FROM attendance WHERE user_id = :x")
stmt = stmt.bindparams(x="1")
res = session.execute(stmt).all()
🌐
SQLAlchemy
docs.sqlalchemy.org › en › 13 › core › connections.html
Working with Engines and Connections — SQLAlchemy 1.3 Documentation
The Connection.execute() method can of course accommodate more than that, including the variety of SQL expression constructs described in SQL Expression Language Tutorial. ... This section describes how to use transactions when working directly with Engine and Connection objects.
🌐
Hexmos
hexmos.com › freedevtools › c › python › sqlalchemy
SQLAlchemy Text Module - Execute Raw SQL Cheatsheet | python Reference | Online Free DevTools
statement = text("""INSERT INTO book(id, title, primary_author) VALUES(:id, :title, :primary_author)""") ... for line in data: ... con.execute(statement, **line) ... <sqlalchemy.engine.cursor.LegacyCursorResult object at 0x10106cf50> <sqlalchemy.engine.cursor.LegacyCursorResult object at ...
🌐
TestDriven.io
testdriven.io › tips › e326346d-58d0-44e0-9508-3ac89d715907
Tips and Tricks - Execute raw SQL queries in SQLAlchemy | TestDriven.io
You can use raw queries while still using SQLAlchemy models. ... user = session.query(Course).from_statement( text("""SELECT * FROM courses where title=:title""") ).params(title="Scalable FastAPI Applications on AWS").all()
🌐
SQLAlchemy
docs.sqlalchemy.org › en › 21 › faq › sqlexpressions.html
SQL Expressions — SQLAlchemy 2.1 Documentation
The SQLAlchemy project cannot be tasked with duplicating this functionality for every datatype for all backends, as this is redundant work which also incurs significant testing and ongoing support overhead. Stringifying with bound parameters inlined for specific databases suggests a usage that is actually passing these fully stringified statements onto the database for execution...
🌐
PlanetScale
planetscale.com › blog › using-mysql-with-sql-alchemy-hands-on-examples
Using MySQL with SQLAlchemy: Hands-on Examples — PlanetScale
Now that you have the connection, you can execute any SQL statement that works on your database by importing the text function from SQLAlchemy. Add from sqlalchemy import text in your Python file.
🌐
SQLAlchemy
docs.sqlalchemy.org › en › 21 › core › tutorial.html
SQL Expression Language Tutorial — SQLAlchemy 2.1 Documentation
This page is the previous home of the SQLAlchemy 1.x Tutorial. As of 2.0, SQLAlchemy presents a revised way of working and an all new tutorial that presents Core and ORM in an integrated fashion using all the latest usage patterns.