A one-page Python 3 cheat sheet for DBAs and anyone starting with Python. Every example runs as shown in Python 3.9 or later.
Running Python
python3 --version python3 # interactive shell, exit() to leave python3 myscript.py # run a script # Virtual environment: one per project, keeps packages separate python3 -m venv ~/venvs/dba source ~/venvs/dba/bin/activate pip install oracledb
Variables and types
name = "ORCL" # str
port = 1521 # int
used_pct = 82.5 # float
is_open = True # bool
nothing = None # no value
type(port) # <class 'int'>
int("42"), float("3.5"), str(1521)
Strings
s = " Oracle Database "
s.strip() # 'Oracle Database'
s.lower(), s.upper()
s.replace("Oracle", "PostgreSQL")
"ORA-00600".startswith("ORA-") # True
"a,b,c".split(",") # ['a', 'b', 'c']
"-".join(["2026", "11", "25"]) # '2026-11-25'
db, pct = "ORCL", 82.456
print(f"{db} tablespace is {pct:.1f}% full") # ORCL tablespace is 82.5% full
Lists
dbs = ["ORCL", "TEST", "DEV"]
dbs.append("PROD")
dbs[0] # 'ORCL'
dbs[-1] # 'PROD'
dbs[1:3] # ['TEST', 'DEV']
len(dbs) # 4
"DEV" in dbs # True
sorted(dbs)
dbs.remove("TEST")
Dictionaries
db = {"name": "ORCL", "port": 1521, "version": "19c"}
db["name"] # 'ORCL'
db.get("owner", "unknown") # default if the key is missing
db["port"] = 1522
for key, value in db.items():
print(key, value)
Tuples and sets
point = (10, 20) # tuple: cannot be changed
x, y = point # unpacking
hosts = {"db1", "db2", "db1"} # set: {'db1', 'db2'}, no duplicates
hosts.add("db3")
{"db1", "db2"} & {"db2", "db3"} # {'db2'} intersection
Conditions and loops
if used_pct >= 90:
print("CRITICAL")
elif used_pct >= 80:
print("WARNING")
else:
print("OK")
for db in dbs:
print(db)
for i, db in enumerate(dbs, start=1):
print(i, db)
count = 0
while count < 3:
count += 1
for n in range(5): # 0, 1, 2, 3, 4
if n == 3:
break
Comprehensions
squares = [n * n for n in range(5)] # [0, 1, 4, 9, 16]
usage = {"USERS": 91.2, "SYSAUX": 64.0, "DATA": 88.5}
full = [t for t, pct in usage.items() if pct > 85] # ['USERS', 'DATA']
upper = {db: db.lower() for db in dbs}
Functions
def pct_used(used_mb, total_mb, decimals=1):
"""Return the percentage used."""
return round(used_mb / total_mb * 100, decimals)
pct_used(850, 1000) # 85.0
pct_used(total_mb=1000, used_mb=850, decimals=0)
def log(*messages, level="INFO"):
print(level, *messages)
Errors
try:
pct = pct_used(850, 0)
except ZeroDivisionError:
pct = None
except Exception as e:
print(f"Unexpected error: {e}")
finally:
print("done")
raise ValueError("port must be a number")
Files
with open("alert_ORCL.log") as f: # file closes automatically
for line in f:
if "ORA-" in line:
print(line.rstrip())
with open("report.txt", "w") as f:
f.write("All databases OK\n")
import csv, json
with open("dbs.csv") as f:
for row in csv.DictReader(f):
print(row["name"])
data = json.loads('{"name": "ORCL"}')
text = json.dumps(data, indent=2)
Useful modules
import os, sys, datetime, subprocess, re
os.environ.get("ORACLE_SID")
os.path.exists("/u01/app/oracle")
datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
re.findall(r"ORA-\d{5}", line)
result = subprocess.run(["df", "-h"], capture_output=True, text=True)
print(result.stdout)
sys.exit(1) # exit with an error code
Classes (the basics)
class Database:
def __init__(self, name, port=1521):
self.name = name
self.port = port
def dsn(self, host):
return f"{host}:{self.port}/{self.name}"
orcl = Database("ORCL")
orcl.dsn("dbhost1") # 'dbhost1:1521/ORCL'
Connecting to Oracle with python-oracledb
import getpass
import oracledb
conn = oracledb.connect(user="system",
password=getpass.getpass("Password: "),
dsn="dbhost1:1521/ORCLPDB1")
with conn.cursor() as cur:
cur.execute("""
SELECT tablespace_name, ROUND(used_percent, 1)
FROM dba_tablespace_usage_metrics
WHERE used_percent > :limit
ORDER BY 2 DESC""", limit=80)
for name, pct in cur:
print(f"{name:20} {pct:5.1f}%")
conn.close()
Never put passwords in a script. Ask for them with getpass, read them from an environment variable, or use a wallet or a secrets manager. Always use bind variables (:limit), never string formatting, to pass values into SQL.
Script template
#!/usr/bin/env python3
"""Check something and exit with 0 (OK) or 1 (problem)."""
import sys
def main():
problems = []
# ... checks go here ...
for p in problems:
print(p)
return 1 if problems else 0
if __name__ == "__main__":
sys.exit(main())
More DBA scripts are in my GitHub repository: github.com/sbajwa55/dba-scripts. For help with Oracle, cloud migrations or AWS, visit Bajwa Consulting Services.

No comments:
Post a Comment