Decebal
Decebal

Reputation: 1419

Mysql connection with python in a class

i'm trying to connect to a database building a class connection()saved in local folder in file utils.py .This is what i worked so far of it:

class connection:

    def __init__(self):
        self.conn = MySQLdb.connect(host = "localhost",user = "xxx",
                             passwd = "xxx", db = "xxx",
                             cursorclass=MySQLdb.cursors.DictCursor)

    def TearDown(self):
        self.conn.close()
    def nume(self):
        return self.conn

and this is where i use it in code:

from utils import execute_sql,connection
con = connection.nume()
cursor = con.cursor()
....
cursor.execute(sql)
...
connection.TearDown()

i tryed several more but this way was the simplest, still getting some errors that i struggle with;

Upvotes: 0

Views: 3737

Answers (1)

Jeremy Brown
Jeremy Brown

Reputation: 18338

The glaring issue is that you need to instantiate your "connection" class before calling methods.

from utils import execute_sql,connection
my_con = connection()
con = my_con.nume()
cursor = con.cursor()
....
cursor.execute(sql)
...
connection.TearDown()

As a side note - your connection class seems a bit superfluous.

Upvotes: 2

Related Questions