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

+20 -19
View File
@@ -1,12 +1,12 @@
"""
CRUD operations for GUARDIAN, STUDENT and ATTENDANCE.
Every function takes an open pymysql connection as its first argument and
manages its own commit/rollback. All functions return plain data
(dicts/lists/bool) so this module has no dependency on the UI layer.
Every function takes an open mysql-connector-python connection as its first
argument and manages its own commit/rollback. All functions return plain
data (dicts/lists/bool) so this module has no dependency on the UI layer.
"""
import pymysql
import mysql.connector
class CrudError(Exception):
@@ -20,33 +20,34 @@ def _run(conn, sql, params=None, fetch=None):
fetch: None (no fetch), 'one', or 'all'
Translates common MySQL errors into CrudError with a friendly message.
"""
cur = conn.cursor(dictionary=True)
try:
with conn.cursor() as cur:
cur.execute(sql, params or ())
result = None
if fetch == "one":
result = cur.fetchone()
elif fetch == "all":
result = cur.fetchall()
conn.commit()
return result if fetch else cur.rowcount
except pymysql.err.IntegrityError as e:
cur.execute(sql, params or ())
result = None
if fetch == "one":
result = cur.fetchone()
elif fetch == "all":
result = cur.fetchall()
conn.commit()
return result if fetch else cur.rowcount
except mysql.connector.errors.IntegrityError as e:
conn.rollback()
code = e.args[0] if e.args else None
if code == 1062:
if e.errno == 1062:
raise CrudError("A record with that primary/unique key already exists.")
if code in (1451, 1452):
if e.errno in (1451, 1452):
raise CrudError(
"That operation violates a foreign key constraint "
"(referenced record missing, or still referenced by other rows)."
)
raise CrudError(f"Database integrity error: {e}")
except pymysql.err.DataError as e:
except mysql.connector.errors.DataError as e:
conn.rollback()
raise CrudError(f"Invalid data for one or more fields: {e}")
except pymysql.err.MySQLError as e:
except mysql.connector.Error as e:
conn.rollback()
raise CrudError(f"Database error: {e}")
finally:
cur.close()
# ---------------------------------------------------------------- GUARDIAN --