import sys
import pymssql
import logging
import logging.handlers
logger = logging.getLogger("DataBase")
logger.setLevel(logging.INFO)
file_log = logging.handlers.RotatingFileHandler('./example.log', maxBytes=10485760, backupCount=5)
file_log.setLevel(logging.DEBUG)
console_log = logging.StreamHandler()
console_log.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_log.setFormatter(formatter)
console_log.setFormatter(formatter)
logger.addHandler(file_log)
logger.addHandler(console_log)
class DataBase:
def __init__(self, server, db, usr, pwd):
self.logger = logging.getLogger("DataBase")
try:
self.con = pymssql.connect(host=server, user=usr, password=pwd, database=db)
self.set_autocommit_mode(False)
self.cursor = self.con.cursor()
self.cursor.execute("SELECT @@SERVERNAME")
self.cursor.execute("SELECT DB_NAME()")
self.db_name = self.cursor.fetchone()[0]
self.cursor.execute("SELECT @@VERSION")
except pymssql.Error as dbe:
try:
self.logger.error(" Error [%d]: %s" % (dbe.args[0], dbe.args[1]))
except IndexError:
self.logger.error(" Error: %s" % str(dbe))
sys.exit(1)
def get_autocommit_mode(self):
return self.con.autocommit_state
def set_autocommit_mode(self, mode):
self.con.autocommit(mode)
def start_transaction(self):
self.execute("BEGIN TRANSACTION")
def commit_transaction(self):
self.execute("COMMIT TRANSACTION")
def execute(self, sql):
"""Runs an sql query. Returns None on error."""
try:
self.cursor.execute(sql)
except pymssql.Error as dbe:
try:
self.logger.error(" Error [%d]: %s" % (dbe.args[0], dbe.args[1]))
except IndexError:
self.logger.error(" Error: %s" % str(dbe))
raise
return None
return self.cursor.rowcount
def close(self):
try:
if self.cursor:
self.cursor.close()
if self.con:
self.con.close()
except pymssql.Error as dbe:
try:
self.logger.error("Error [%d]: %s" % (dbe.args[0], dbe.args[1]))
except IndexError:
self.logger.error("Error: %s" % str(dbe))
if __name__ == "__main__":
# Test Database Class
db = DataBase(r"localhost", r"dbname", r"user", r"password")
db.start_transaction()
db.execute("INSERT INTO some_table (name, data1, data2) VALUES ('someone', 'some data', 'more data')")
db.commit_transaction()
db.close()
sys.exit()