updated to mysql-connector-python

This commit is contained in:
srikar committed 2026-09-27 10:36:18 -07:00
1 parent 65691a0aee
commit 4bc9b87317
6 files changed
+80 -68

No files matched your search

+25 -13
View File
@@ -13,8 +13,8 @@ Schema notes:
import sys
import pymysql
import pymysql.cursors
import mysql.connector
from mysql.connector import errorcode
import config
@@ -61,20 +61,25 @@ TABLE_ORDER = ["GUARDIAN", "STUDENT", "ATTENDANCE"]
def connect_server(database=None):
"""Connect to the MySQL server (optionally selecting a database)."""
try:
conn = pymysql.connect(
conn = mysql.connector.connect(
host=config.DB_HOST,
port=config.DB_PORT,
user=config.DB_USER,
password=config.DB_PASSWORD,
database=database,
connect_timeout=config.DB_CONNECT_TIMEOUT,
cursorclass=pymysql.cursors.DictCursor,
connection_timeout=config.DB_CONNECT_TIMEOUT,
autocommit=False,
)
return conn
except pymysql.err.OperationalError as e:
print(f"\n[ERROR] Could not connect to MySQL server at "
f"{config.DB_HOST}:{config.DB_PORT} as user '{config.DB_USER}'.")
except mysql.connector.Error as e:
if e.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print(f"\n[ERROR] Access denied for user '{config.DB_USER}' — check "
f"DB_USER/DB_PASSWORD.")
elif database and e.errno == errorcode.ER_BAD_DB_ERROR:
print(f"\n[ERROR] Database '{database}' does not exist.")
else:
print(f"\n[ERROR] Could not connect to MySQL server at "
f"{config.DB_HOST}:{config.DB_PORT} as user '{config.DB_USER}'.")
print(f" Details: {e}")
sys.exit(1)
@@ -83,7 +88,8 @@ def ensure_database():
"""Verify the student_db database exists; create it if it does not."""
conn = connect_server(database=None)
try:
with conn.cursor() as cur:
cur = conn.cursor()
try:
cur.execute("SHOW DATABASES LIKE %s", (config.DB_NAME,))
exists = cur.fetchone() is not None
if exists:
@@ -96,23 +102,29 @@ def ensure_database():
)
conn.commit()
print(f"[OK] Database '{config.DB_NAME}' created.")
finally:
cur.close()
finally:
conn.close()
def ensure_tables(conn):
"""Verify each required table exists; create any that are missing."""
with conn.cursor() as cur:
cur.execute("SHOW TABLES")
existing = {row[f"Tables_in_{config.DB_NAME}"] for row in cur.fetchall()}
cur = conn.cursor()
cur.execute("SHOW TABLES")
existing = {row[0] for row in cur.fetchall()}
cur.close()
for table in TABLE_ORDER:
if table in existing:
print(f"[OK] Table '{table}' found.")
else:
print(f"[..] Table '{table}' not found. Creating it...")
with conn.cursor() as cur:
cur = conn.cursor()
try:
cur.execute(TABLE_DEFINITIONS[table])
finally:
cur.close()
conn.commit()
print(f"[OK] Table '{table}' created.")