python-mylib/mylib/mysql.py

61 lines
1.4 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
""" MySQL client """
import logging
import sys
import MySQLdb
2023-01-06 19:36:14 +01:00
from MySQLdb._exceptions import Error
log = logging.getLogger(__name__)
2021-05-19 19:19:57 +02:00
class MyDB:
""" MySQL client """
host = ""
user = ""
2021-05-19 19:19:57 +02:00
pwd = ""
db = ""
con = 0
def __init__(self, host, user, pwd, db):
self.host = host
self.user = user
2021-05-19 19:19:57 +02:00
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
2023-01-06 19:36:14 +01:00
except Error:
log.fatal('Error connecting to MySQL server', exc_info=True)
sys.exit(1)
2021-05-19 19:19:57 +02:00
def doSQL(self, sql):
""" Run INSERT/UPDATE/DELETE/... SQL query """
cursor = self.con.cursor()
try:
cursor.execute(sql)
self.con.commit()
return True
2023-01-06 19:36:14 +01:00
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()
2023-01-06 19:36:14 +01:00
except Error:
log.error('Error during SQL request "%s"', sql, exc_info=True)
return False