Run plain SQL query and get results using SQLAlchemy

tech kamar
1 min readApr 27, 2024

Follow these steps below to run raw/plain SQL query and get output using SQLALchemy

  1. Import libraries
import urllib.parse # For making sure passwords are parsed properly to support special characters
from sqlalchemy import create_engine
from sqlalchemy.sql import text

2. Create Engine (I am using postgreSQL here)

DB_NAME = "college_db"
DB_USER = "admin"
DB_PASS = urllib.parse.quote_plus("admin@12345") #Password has special characters. so need to be parsed
DB_HOST = "localhost"
DB_PORT = "5432"

SQLALCHEMY_DATABASE_URL = (
"postgresql://"
+ DB_USER
+ ":"
+ DB_PASS
+ "@"
+ DB_HOST
+ ":"
+ DB_PORT
+ "/"
+ DB_NAME
)

# Pool Recycle and Pre ping is used to make sure that there is no connection issues
engine = create_engine(SQLALCHEMY_DATABASE_URL,pool_size=5,pool_recycle=1800,pool_pre_ping=True)

3. Create and Execute the SQL Query

query = "SELECT name,subject,score FROM exam"
with engine.connect() as con:
rs = con.execute(text(f"""{query}"""))
for row in rs:
print("Name = "+str(row[0]))
print("Subject = "+str(row[1]))
print("Score = "+str(row[2]))

Now see the whole file

import urllib.parse # For making sure passwords are parsed properly to support special characters
from sqlalchemy import create_engine
from sqlalchemy.sql import text

DB_NAME = "college_db"
DB_USER = "admin"
DB_PASS = urllib.parse.quote_plus("admin@12345")
DB_HOST = "localhost"
DB_PORT = "5432"

SQLALCHEMY_DATABASE_URL = (
"postgresql://"
+ DB_USER
+ ":"
+ DB_PASS
+ "@"
+ DB_HOST
+ ":"
+ DB_PORT
+ "/"
+ DB_NAME
)
engine = create_engine(SQLALCHEMY_DATABASE_URL,pool_size=5,pool_recycle=1800,pool_pre_ping=True)

query = "SELECT name,subject,score FROM exam"
with engine.connect() as con:
rs = con.execute(text(f"""{query}"""))
for row in rs:
print("Name = "+str(row[0]))
print("Subject = "+str(row[1]))
print("Score = "+str(row[2]))

Thanks for reading :)

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response