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
🌐
Joaodlf
joaodlf.com › python-just-write-sql
Python: Just write SQL - joaodlf.com
August 10, 2023 - In this post, I will aim to approach SQL in Python in the same vein as Go:
🌐
Atlassian
atlassian.com › data › notebook › how-to-execute-raw-sql-in-sqlalchemy
How to Execute Raw SQL in SQLAlchemy | Atlassian
The alternative method is to skip using text() and pass a raw SQL string to the .execute() method. For example, here we’ll use .execute() to view the new records we inserted above:
🌐
DataCamp
campus.datacamp.com › courses › introduction-to-relational-databases-in-python › basics-of-relational-databases
Selecting data from a Table: raw SQL | Python
from sqlalchemy import create_engine engine = create_engine('sqlite:///census.sqlite') # Create a connection on engine connection = ___ # Build select statement for census table: stmt stmt = ____ # Execute the statement and fetch the results: results results = ____ # Print results print(____)
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})
🌐
DEV Community
dev.to › propelauth › libraries-for-writing-raw-sql-safely-2op2
Libraries for writing raw SQL safely - DEV Community
September 13, 2024 - Prisma recently released TypedSQL — a “a new way to write raw SQL queries in a type-safe way.” They mention that part of the inspiration was both SQLx and PgTyped, so I am excited to try it out! A library I enjoy when I switch to Python is PugSQL (Python).
🌐
Hacker News
news.ycombinator.com › item
Records: Python library for making raw SQL queries to Postgres databases | Hacker News
February 11, 2016 - https://github.com/cjauvin/little_pger · I have been using this for myself for quite some time, but feedback would be very appreciated
🌐
Medium
medium.com › @adnan-kaya › fastapi-crud-app-with-raw-sql-part-1-d62bad80a386
FastAPI CRUD app with Raw SQL | Part 1 | by Adnan Kaya | Medium
July 7, 2023 - Psycopg2 is a widely used and well-established Python adapter for PostgreSQL that provides a simple and efficient way to work with PostgreSQL databases. Raw SQL refers to the practice of writing SQL queries directly in your application code, without the use of Object-Relational Mapping (ORM) libraries.
🌐
GitHub
github.com › racinette › querky
GitHub - racinette/querky: Turn your raw SQL queries into fully type annotated Python functions with a single decorator.
Turn your SQL queries into type annotated Python functions and autogenerated types with a single decorator. This example shows what querky SQL functions look like.
Author   racinette
Find elsewhere
🌐
ZetCode
zetcode.com › db › sqlalchemy › rawsql
Raw SQL in SQLAlchemy
It also allows to execute raw SQL statements when needed. In the first example, we connect to an in-memory SQLite database and execute a simple SQL statement. ... #!/usr/bin/python # -*- coding: utf-8 -*- from sqlalchemy import create_engine eng = create_engine('sqlite:///:memory:') with ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-execute-raw-sql-in-sqlalchemy
How to Execute Raw SQL in SQLAlchemy - GeeksforGeeks
February 28, 2022 - 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. The SQLAlchemy query shown in the below code selects all rows where the book price is greater than Rs.
🌐
MLJAR
mljar.com › notebooks › postgresql-python-raw-query
Run raw SQL query in python
Raw query is very powerful but requires knowledge of SQL, you can look at other database recipes and have a guess how to write your own queries. If you are experienced user this should be the place right for you. All code recipes used in this notebook are listed below. You can click them to check their documentation. ... List of packages that need to be installed in your Python environment to run this notebook.
🌐
TestDriven.io
testdriven.io › tips › e326346d-58d0-44e0-9508-3ac89d715907
Tips and Tricks - Execute raw SQL queries in SQLAlchemy | TestDriven.io
Python SQLAlchemy tip: You can use raw queries while still using SQLAlchemy models. For example · user = session.query(Course).from_statement( text("""SELECT * FROM courses where title=:title""") ).params(title="Scalable FastAPI Applications on AWS").all() View All Tips ·
🌐
Django Documentation
docs.djangoproject.com › en › 5.1 › topics › db › sql
Performing raw SQL queries | Django documentation | Django
In the example we’ve assumed that the Person model lives in an app named myapp, so its table would be myapp_person. For more details check out the documentation for the db_table option, which also lets you manually set the database table name. ... No checking is done on the SQL statement that is passed in to .raw().
🌐
Dataiku Community
community.dataiku.com › questions & discussions › using dataiku
Running SQL statements with Python? — Dataiku Community
June 7, 2022 - from dataiku import SQLExecutor2 sqlcon = SQLExecutor2(dataset="output_table") sql_str = """INSERT INTO "public"."output_table" (col_one, col_two) VALUES('value_one', 'value_two')""" sqlcon.query_to_df(sql_str, post_queries=['COMMIT'])
🌐
DataCamp
datacamp.com › tutorial › tutorial-how-to-execute-sql-queries-in-r-and-python
How to Execute SQL Queries in Python and R Tutorial | DataCamp
April 4, 2022 - Learn easy and effective ways to run SQL queries in Python and R for data analysis and database management.
🌐
Real Python
realpython.com › python-sql-libraries
Introduction to Python SQL Libraries – Real Python
March 25, 2024 - You can see that creating tables in SQLite is very similar to using raw SQL. All you have to do is store the query in a string variable and then pass that variable to cursor.execute(). ... You’ll use the mysql-connector-python Python SQL module to create tables in MySQL.
🌐
Medium
medium.com › @melihcolpan › sqlalchemy-vs-raw-sql-queries-performance-comparison-and-best-practices-caba49125630
SQLAlchemy vs. Raw SQL Queries: Performance Comparison and Best Practices | by Melih Çolpan | Medium
October 1, 2024 - The following operations were performed using both SQLAlchemy and Raw SQL queries: 1. Simple Select Query: Fetching records from a single table. 2. Insert Operation: Inserting multiple rows into a table. 3. Complex Join Operation: Performing a join operation across multiple tables. Code Setup The setup consisted of creating a sample database schema using SQLAlchemy and executing each of the test queries. Below is an example code snippet for the test setup: