How should i organize mysql.connector in project

43 Views Asked by At

I'm trying to organize MySQL.connector functions in my project, and I'm currently using a separated .py file in which I created a Mysql class and create a bunch of functions. the main question is, is it right? how should I do it?

import mysql.connector


class Mysql:
    def __init__(self, host='localhost', user='root', pwd='', db=''):
        self.host = host
        self._user = user
        self._pwd = pwd
        self.db = db

    def open(self):
        try:
            self.mydb = mysql.connector.connect(
                host=self.host, user=self._user, passwd=self._pwd, database=self.db)
        except:
            print("could not connect to server")
        else:
            print("connected successfully")
            self.mycursor = self.mydb.cursor()

    def select(self, con, tab, num, *args):
        self.mycursor.execute(f"select {con} from {tab} {' '.join(args)}")
        if num == 0:
            val = self.mycursor.fetchall()
        else:
            val = self.mycursor.fetchmany(num)
        self.mycursor.close()
        self.mydb.close()
        return val

    def delete(self, con, tab, id):
        self.mycursor.execute(f"delete from {tab} where id = {id}")
        self.mycursor.close()
        self.mydb.close()


if __name__ == "__main__":
    db = Mysql('localhost', 'my_user', 'mypass', 'wine')
    db.open()
    val = db.select('*', 'wine_eval', 1, "order by id")
    print(val)
    db.open()
    val = db.select('*', 'wine_eval', 1, "order by id")
    print(val)

0

There are 0 best solutions below