0

I have simple class to fetch query from database .

# myClass.py
class DB:
    def __init__ (self, host, user, password):
        self.conn = MySQLdb.connect("localhost","****","****","***")
        self.conn.set_character_set('utf8mb4')
        cursor = self.conn.cursor()
        cursor.execute('SET NAMES utf8mb4;')
        cursor.execute('SET CHARACTER SET utf8mb4;')
        cursor.execute('SET character_set_connection=utf8mb4;')
    def query(self, q):
            cursor = self.conn.cursor()
            cursor.execute(q)
            return cursor

If I use the below query with it works ok,

from myClass import DB
q = DB("..", "..", "..", "..")
_fetch = q.query("... ")

However if I would like to get rid of the second line since I am declaring user, pass, host .. in myClass.py

So, when I try

from myClass import DB
_fetch = DB.query("... ")

it won't allow me to connect, even if I remove the self, keyword for query

2 Answers2

0

You could try something like:

# myClass.py

# code will be executed only once a the first import 
conn = MySQLdb.connect("localhost","****","****","***")
conn.set_character_set('utf8mb4')
cursor = conn.cursor()    
cursor.execute('SET NAMES utf8mb4;')
cursor.execute('SET CHARACTER SET utf8mb4;')
cursor.execute('SET character_set_connection=utf8mb4;')

class DB:
    # class attribute shared among all DB instance
    cursor = conn.cursor()
    # class method
    @classmethod
    def query(cls, q):
        cls.cursor.execute(q)
        return cursor
Ali SAID OMAR
  • 4,760
  • 4
  • 29
  • 53
0

You can create class object ones and then just import and use it:

# myClass.py
class DB:
    def __init__ (self, host, user, password):
        # ...

db = DB("..", "..", "..", "..")  # Create object ones.

Somewhere in other module:

from myClass import db

db.query("... ")
Mikhail Gerasimov
  • 27,590
  • 10
  • 86
  • 127
  • Not sure if it is a good practice to add `db = DB('..')` at the end of `myClass.py` I would like to learn python the proper way and this seems a hack.. –  Mar 16 '16 at 13:41
  • 1
    It's not a hack : https://pythonconquerstheuniverse.wordpress.com/2010/10/20/a-globals-class-pattern-for-python/ – Ali SAID OMAR Mar 16 '16 at 13:45
  • @ANW, it's not a hack. If you don't like it, only way I can advice is to remove params from init and make your DB class singleton. http://stackoverflow.com/q/6760685/1113207 – Mikhail Gerasimov Mar 16 '16 at 13:53
  • @germn I have spent 2 hours in this, it is like there is almost 0 ways it can work without some error. I even tried your solution and placed `db = DB()` in the last line of `myClass.py` but it still won't work. –  Mar 16 '16 at 13:57
  • @ANW Solution in my answer can't be reason. What happens after you created `db` and use it for queries? – Mikhail Gerasimov Mar 16 '16 at 14:03