python-mylib/mylib/mysql.py
Benjamin Renard ad04357c6b Code cleaning
2023-01-06 19:38:32 +01:00

61 lines
1.4 KiB
Python

# -*- coding: utf-8 -*-
""" MySQL client """
import logging
import sys
import MySQLdb
from MySQLdb._exceptions import Error
log = logging.getLogger(__name__)
class MyDB:
""" MySQL client """
host = ""
user = ""
pwd = ""
db = ""
con = 0
def __init__(self, host, user, pwd, db):
self.host = host
self.user = user
self.pwd = pwd
self.db = db
def connect(self):
""" Connect to MySQL server """
if self.con == 0:
try:
con = MySQLdb.connect(self.host, self.user, self.pwd, self.db)
self.con = con
except Error:
log.fatal('Error connecting to MySQL server', exc_info=True)
sys.exit(1)
def doSQL(self, sql):
""" Run INSERT/UPDATE/DELETE/... SQL query """
cursor = self.con.cursor()
try:
cursor.execute(sql)
self.con.commit()
return True
except Error:
log.error('Error during SQL request "%s"', sql, exc_info=True)
self.con.rollback()
return False
def doSelect(self, sql):
""" Run SELECT SQL query and return result as dict """
cursor = self.con.cursor()
try:
cursor.execute(sql)
return cursor.fetchall()
except Error:
log.error('Error during SQL request "%s"', sql, exc_info=True)
return False