Home > Back-end >  Python MySQL - best practises. Create & connect
Python MySQL - best practises. Create & connect

Time:01-30

could you advise me on best practices on how to deal with MySQL class in Python application?

class DBClient:
    def __init__(self, db_name=None):
        self.conn = None
        self.db_name = db_name
        self.__create_connection()

    def __create_connection(self):
        try:
            self.conn = mysql.connector.connect(
                host="127.0.0.1",
                port=3306,
                user="root",
                password="password",
                database=self.db_name
            )
            print('DB Connection successful')
        except InterfaceError as e:
            exit(e)
        except mysql.connector.Error as err:
            if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
                print("Something is wrong with your user name or password")
            elif err.errno == errorcode.ER_BAD_DB_ERROR:
                print("Database does not exist")
            else:
                print(err)

    def __del__(self):
        if self.conn:
            self.conn.close()

    def __commit(self):
        self.conn.commit()

DBClient(config.DB_NAME).create_items_table()

in general the problem is:

  1. as you noticed the method __create_connestion specified to which database we would like to connect. The problem is if the the database is not created. How to avoid code duplication in that scenario:
  • connect to DB
  • if db is not created -> create that
  • if db is created -> connect

CodePudding user response:

It is not a good idea to create a database automatically, it is an action that is better to do yourself. Never put credentials in code, use environment variables instead, please have a look at this module Dotenv

CodePudding user response:

so if I understand correctly it is better to have sth like this in main:

if __name__ == '__main__':
        DBClient(config.DB_NAME).to_do_something()

and have separate script, lets say setup_db.py which is going to create a database and schema?

  • Related