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 - This comes naturally due to the sql package: A common interface to be used alongside database drivers. It’s very common to see actual SQL in Go, even in large projects. On the other hand, Python does not have anything in the standard library that supports database interaction, this has always been a problem for the community to solve.
🌐
Atlassian
atlassian.com › data › notebook › how-to-execute-raw-sql-in-sqlalchemy
How to Execute Raw SQL in SQLAlchemy | Atlassian
SQLAlchemy is a SQL tool built with Python that provides developers with an abundance of powerful features for designing and managing high-performance databases. We’ll briefly explore how to use SQLAlchemy and then dive deeper into how to execute raw SQL statements from within the comfort ...
Discussions

python - How to execute raw SQL in Flask-SQLAlchemy app - Stack Overflow
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 More on stackoverflow.com
🌐 stackoverflow.com
Records: Python library for making raw SQL queries to Postgres databases
https://github.com/cjauvin/little_pger · I have been using this for myself for quite some time, but feedback would be very appreciated More on news.ycombinator.com
🌐 news.ycombinator.com
129
257
February 11, 2016
python - How to query with raw SQL using Session or engine - Stack Overflow
With Parent and Child tables: from sqlalchemy import Column, ForeignKey, String, create_engine, desc, asc from sqlalchemy.ext.declarative import declarative_base import uuid Base = declarative_ba... More on stackoverflow.com
🌐 stackoverflow.com
Do Programmers Still Write Raw SQL?

Definitely yes. Any large enough project has That One Query.

More on reddit.com
🌐 r/Python
22
3
March 7, 2023
🌐
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).
🌐
DataCamp
campus.datacamp.com › courses › introduction-to-relational-databases-in-python › basics-of-relational-databases
Selecting data from a Table: raw SQL | Python
Using what we just learned about SQL and applying the .execute() method on our connection, we can leverage a raw SQL query to query all the records in our census table. The object returned by the .execute() method is a ResultProxy.
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})
🌐
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 ... 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....
🌐
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
Find elsewhere
🌐
Django Documentation
docs.djangoproject.com › en › 5.2 › topics › db › sql
Performing raw SQL queries | Django documentation | Django
Django gives you two ways of performing raw SQL queries: you can use Manager.raw() to perform raw queries and return model instances, or you can avoid the model layer entirely and execute custom SQL directly.
🌐
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.
🌐
PyPI
pypi.org › project › sqla-raw
sqla-raw
JavaScript is disabled in your browser · Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
Reddit
reddit.com › r/python › is it bad practice for my flask api to run raw sql queries against my db to get/post data?
r/Python on Reddit: Is it bad practice for my flask API to run raw SQL queries against my DB to get/post data?
January 24, 2022 -

I wrote a very small flask API to serve data from a MySQL database to a frontend application as a pet project.

When a user accesses an endpoint and provides arguments, the script reads a SQL query stored in a .sql file, formats it with said provided arguments, and runs it via mysql-connector-python.

Examples (syntax may be incorrect, this is not from my code, just for demonstration)

conn = mysql.connector.connect(<...>)
cursor = conn.cursor()

@app.route("/users", methods=["GET"])
def get_user():
    user_name = request.args.get('name')

    # open SQL file, read query, and format
    with open("./sql/example_sql_query.sql") as f:
        query = f.read()
    cursor.execute(query.format(name=user_name))
    result = cursor.fetchone()
    
    < logic to return resulting data >

Example SQL query

SELECT *
  FROM users
 WHERE user_name = {name}

I ask because from all examples I've seen, I've never seen anyone doing this. Everyone seems to use SQLAlchemy, but given my current role as a SQL dev I'm much more comfortable using raw SQL to generate results. This method has been working so far.

I'd like to hear your thoughts!

🌐
Readthedocs
djangodocs.readthedocs.io › en › latest › topics › db › sql.html
Performing raw SQL queries — Django 1.5 documentation
Django gives you two ways of performing raw SQL queries: you can use Manager.raw() to perform raw queries and return model instances, or you can avoid the model layer entirely and execute custom SQL directly.
🌐
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 ·
🌐
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 eng.connect() as con: rs = con.execute('SELECT 5') data = rs.fetchone()[0] print "Data: %s" % data
🌐
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.
🌐
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'])
🌐
GitHub
github.com › racinette › querky
GitHub - racinette/querky: Turn your raw SQL queries into fully type annotated Python functions with a single decorator.
Each of your queries will become type hinted, each of them will return a real Python object, and you can call these queries as regular Python functions. Every time you change your database schema or queries, you can now expect the changes to propagate throughout your code. Because of that, refactoring SQL-dependent code has never been easier.
Author   racinette