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
🌐
SQLAlchemy
docs.sqlalchemy.org › en › 20 › core › connections.html
Working with Engines and Connections — SQLAlchemy 2.0 Documentation
See Managing Transactions for further information. The Connection object always emits SQL statements within the context of a transaction block. The first time the Connection.execute() method is called to execute a SQL statement, this transaction is begun automatically, using a behavior known ...
🌐
SQLAlchemy
docs.sqlalchemy.org › en › 13 › core › connections.html
Working with Engines and Connections — SQLAlchemy 1.3 Documentation
The SQL expression object itself references an Engine or Connection known as the bind, which it uses in order to provide so-called “implicit” execution services. ... from sqlalchemy import MetaData, Table, Column, Integer meta = MetaData() users_table = Table('users', meta, Column('id', ...
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})
🌐
GitHub
github.com › openai › openai-agents-python
GitHub - openai/openai-agents-python: A lightweight, powerful framework for multi-agent workflows · GitHub
2 weeks ago - SQLAlchemy · any-llm and LiteLLM · We also rely on the following tools to manage the project: uv and ruff · mypy and Pyright · pytest and Coverage.py ·
Starred by 26.1K users
Forked by 4K users
Languages   Python
🌐
SQLAlchemy
docs.sqlalchemy.org › en › 21 › orm › events.html
ORM Events — SQLAlchemy 2.1 Documentation
3 weeks ago - Execute after a commit has occurred. ... from sqlalchemy import event @event.listens_for(SomeSessionClassOrObject, 'after_commit') def receive_after_commit(session): "listen for the 'after_commit' event" # ...
🌐
Duke
fintechpython.pages.oit.duke.edu › jupyternotebooks › 5-Databases › 4-SQLAlchemy-Engine.html
SQLAlchemy and the Database Engine — Programming for Financial Technology
1with engine.connect() as connection: ... = result.all() 4 print(len(all_rows)) ... By default, SQLAlchemy places the connection into a transaction and you will need to explicitly commit the transaction for the change to persist....
🌐
SQL Online AiDE
sqliteonline.com
SQL Online IDE - Fast SQL Editor | SQL Compiler
SQL OnLine - SQLite, DuckDB, PGLite, MariaDB / MySQL, PostgreSQL, MS SQL Server. AI error analysis, User-friendly interface for Data Science. No registration for start, No DownLoad, No Install. | sql compiler, federated queries, temporal query federation, BI Analytics
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › sqlalchemy › sqlalchemy_quick_guide.htm
SQLAlchemy - Quick Guide
We can use this select object as a parameter to execute() method of connection object as shown in the code below − ... The resultant variable is an equivalent of cursor in DBAPI. We can now fetch records using fetchone() method. ... from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String engine = create_engine('sqlite:///college.db', echo = True) meta = MetaData() students = Table( 'students', meta, Column('id', Integer, primary_key = True), Column('name', String), Column('lastname', String), ) s = students.select() conn = engine.connect() result = conn.execute(s) for row in result: print (row)
🌐
GitHub
github.com › sqlalchemy › sqlalchemy › issues › 5434
How to get value from sqlalchemy .execute() method? Python + Sqlalchemy+ MS SQL server · Issue #5434 · sqlalchemy/sqlalchemy
July 2, 2020 - def return_csv_status_db(db_instance, name_of_db_instance_tabledict, csvfile_path): table_dict = db_instance[name_of_db_instance_tabledict] csvfile_name = csvfile_path.name sql = db.select([table_dict['table'].c.CSV_STATUS]).where(table_dict['table'].c.CSV_FILENAME == csvfile_name) result = table_dict['engine'].execute(sql) print(result) Whenever I print result, it returns: <sqlalchemy.engine.result.ResultProxy object at 0x0000005E642256C8> How can I extract the value of the select statement?
Author   edo101
🌐
PyPI
pypi.org › project › fastapi
fastapi · PyPI
Then click on the "Execute" button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen:
      » pip install fastapi
    
Published   Apr 23, 2026
Version   0.136.1
🌐
Atlassian
atlassian.com › data › notebook › how-to-execute-raw-sql-in-sqlalchemy
How to Execute Raw SQL in SQLAlchemy | Atlassian
This tutorial offers a practical approach to executing raw SQL queries in SQLAlchemy, providing clear examples and tips for efficient database management.
🌐
Better Programming
betterprogramming.pub › how-to-execute-plain-sql-queries-with-sqlalchemy-627a3741fdb1
How to Execute Plain SQL Queries With SQLAlchemy in Python | by Lynn G. Kwong | Better Programming
August 25, 2023 - For SQL queries with a lot of JOIN clauses and subqueries, it is much more straightforward to execute them directly than to translate them into complex ORM model-based code. Besides, we can store SQL queries in a file and then execute them with sqlparse and SQLAlchemy.
🌐
SQLAlchemy
docs.sqlalchemy.org › en › 13 › orm › session_transaction.html
Transactions and Connection Management — SQLAlchemy 1.3 Documentation
from sqlalchemy.orm import Session # assume session just constructed sess = Session(bind=engine) # call connection() with options before any other operations proceed. # this will procure a new connection from the bound engine and begin a real # database transaction. sess.connection(executi...
🌐
FastAPI
fastapi.tiangolo.com › tutorial › bigger-applications
Bigger Applications - Multiple Files - FastAPI
And we can add a list of dependencies that will be added to all the path operations in the router and will be executed/solved for each request made to them.
🌐
Webpy
webpy.org › cookbook › sqlalchemy
sqlalchemy (web.py)
import string import random import web from sqlalchemy.exc import OperationalError from sqlalchemy.orm import scoped_session, sessionmaker from models import * urls = ( "/", "add", "/view", "view" ) Session = scoped_session(sessionmaker(bind=engine)) def load_sqla(handler): web.ctx.orm = Session() try: return handler() except OperationalError: web.ctx.orm.rollback() Session.remove() raise except: web.ctx.orm.commit() Session.remove() raise finally: web.ctx.orm.commit() Session.remove() app = web.application(urls, locals()) app.add_processor(load_sqla) class add: def GET(self): web.header('Cont
🌐
W3Schools
w3schools.com › python › python_mysql_getstarted.asp
W3Schools.com
If the above code was executed with no errors, "MySQL Connector" is installed and ready to be used.
🌐
Medium
medium.com › @andresberejnoi › how-to-use-sqlalchemy-and-python-to-read-and-write-to-your-database-andres-berejnoi-e99262fd1b34
How to Use SQLAlchemy and Python to Read and Write to Your Database — Andres Berejnoi | by Andrés Berejnoi | Medium
March 31, 2022 - In today’s post, I will explain how to perform queries on an SQL database using Python. Particularly, I will cover how to query a database with SQLAlchemy, Flask-SQLAlchemy, and Pandas.
🌐
SQLAlchemy
docs.sqlalchemy.org › en › 20 › tutorial › data_select.html
Using SELECT Statements — SQLAlchemy 2.0 Documentation
When using the ORM, particularly with a select() construct that’s composed against ORM entities, we will want to execute it using the Session.execute() method on the Session; using this approach, we continue to get Row objects from the result, however these rows are now capable of including complete entities, such as instances of the User class, as individual elements within each row:
🌐
SQLAlchemy
docs.sqlalchemy.org › en › 21 › tutorial › data_update.html
Using UPDATE and DELETE Statements — SQLAlchemy 2.1 Documentation
The CursorResult class is a subclass of Result which contains additional attributes that are specific to the DBAPI cursor object. An instance of this subclass is returned when a statement is invoked via the Connection.execute() method.