Run plain SQL query and get results using SQLAlchemy
Follow these steps below to run raw/plain SQL query and get output using SQLALchemy
- 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 :)