SHARE
TWEET

Untitled

a guest Apr 1st, 2019 121 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. """
  2. --------------------------------------------------
  3. Connect.py
  4. [program description]
  5. --------------------------------------------------
  6. Author: David Djukic
  7. ID: 160692920
  8. Email: djuk2920@mylaurier.ca
  9. __updated__="2019-02-05"
  10. --------------------------------------------------
  11. """
  12.  
  13. # Imports
  14. from configparser import ConfigParser
  15. from mysql.connector import connect, Error
  16.  
  17.  
  18. class Connect:
  19.     """
  20.     Defines an object for a database connection.
  21.     """
  22.     connection = None
  23.     cursor = None
  24.  
  25.     def __init__(self, option_file):
  26.         """
  27.         -------------------------------------------------------
  28.         Initialize a MySQL database connection object.
  29.         Use: connection = Connect(option_file)
  30.         -------------------------------------------------------
  31.         Parameters:
  32.             option_file - name of option file (str)
  33.         Returns:
  34.             A database connection object (Connect)
  35.         -------------------------------------------------------
  36.         option file must be of the form:
  37.         [database]
  38.         user = ...
  39.         password = ...
  40.         host = ...
  41.         database = ...
  42.         -------------------------------------------------------
  43.         See sample option file at:
  44.         https://bohr.wlu.ca/cp363/samples/dcris.txt
  45.         -------------------------------------------------------
  46.         """
  47.         try:
  48.             # Read the contents of the option file
  49.             config = ConfigParser()
  50.             config.read_file(open(option_file))
  51.             # Extract the database section into a dictionary
  52.             params = dict(config['database'])
  53.             params['raise_on_warnings'] = True
  54.             params['use_unicode'] = True
  55.             params['autocommit'] = True
  56.             # Connect to the database
  57.             if self.connection is None:
  58.                 self.connection = connect(**params)
  59.                 self.cursor = self.connection.cursor()
  60.         except FileNotFoundError:
  61.             raise Exception(
  62.                 "Option file '{}' not found.".format(option_file))
  63.         except KeyError as err:
  64.             if 'database' not in config.sections():
  65.                 raise Exception("Option file missing section 'database'.")
  66.             else:
  67.                 raise err
  68.         except Error as err:
  69.             if err.sqlstate == '28000':
  70.                 raise Exception("Invalid username or password")
  71.             elif err.sqlstate == '42000':
  72.                 raise Exception(
  73.                     "Database '{}' does not exist".format(params['database']))
  74.             else:
  75.                 raise err
  76.  
  77.     def close(self):
  78.         """
  79.         Closes the database connection.
  80.         """
  81.         try:
  82.             self.cursor.close()
  83.             self.connection.close()
  84.             self.connection = None
  85.         except AttributeError:
  86.             raise Exception("Database connection is already closed.")
  87.         return
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top