Post

Using SQLAlchemy ORM

A simple query can be constructed as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import os

from sqlalchemy import MetaData, select, Table

import ds_utils.database_operations as dbo

# CONNECT TO DATABASE
engine = dbo.connect_sql_db(
    driver="pyodbc",
    driver_version=os.environ["ODBC_DRIVER"],
    dialect="mssql",
    server=os.environ["ODBC_SERVER"],
    database=os.environ["ODBC_DATABASE"],
    authentication=os.environ["ODBC_AUTHENTICATION"],
    username=os.environ["AZURE_CLIENT_ID"],
    password=os.environ["AZURE_CLIENT_SECRET"],
)

# SET UP QUERY
metadata = MetaData(schema="core")
person = Table(
    "person",
    metadata,
    autoload_replace=True,
    autoload_with=engine
)
post = Table(
    "post",
    metadata,
    autoload_replace=True,
    autoload_with=engine
)
appointment = Table(
    "appointment",
    metadata,
    autoload_replace=True,
    autoload_with=engine
)

query_name = "David Cameron"

stmt = select(
    person
).join(
    appointment,
    person.columns.id == appointment.columns.person_id
).join(
    post,
    appointment.columns.post_id == post.columns.id
).where(
    person.columns.name == query_name
)

# EXECUTE QUERY
with engine.connect() as connection:
    results = connection.execute(stmt).fetchall()
    print(results)

NB: Using a variable such as query_name is safe against SQL injection risks.

This post is licensed under CC BY 4.0 by the author.