编写面向对象的MySQLdb连接

时间:2012-04-16 22:16:18

标签: python

我正在尝试学习OOP,我通过MySQLdb使用数据库连接作为我的第一个测试。这就是我到目前为止所做的:

class DBConnection:
    def __init__(self, DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME):
        self.host = DB_HOST
        self.port = DB_PORT
        self.name = DB_NAME
        self.user = DB_USER
        self.password = DB_PASSWORD

    def get_conn(self):
        conn = MySQLdb.connect (host = self.DB_HOST, port = self.DB_PORT,
                                db = DB_NAME, user = DB_USER,
                                passwd = DB_PASSWORD)
        return conn

    def get_cursor(self):
        cursor = self.conn.cursor()
        return cursor

    def get_dict_cursor(self):
        dict_cursor = self.conn.cursor(MySQLdb.cursors.DictCursor)
        return dict_cursor  

以上是否有效? self.conn是否引用get_conn()或这是无效的引用。我如何建立与数据库的连接,然后使用python shell获取游标?

1 个答案:

答案 0 :(得分:5)

您尚未在任何地方定义self.conn。您只是将conn设置为get_conn内的本地内容。在构造函数中定义self.conn,然后更新get_conn以设置self.conn。像这样:

class DBConnection:
    def __init__(self, DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME):
        self.host = DB_HOST
        self.port = DB_PORT
        self.name = DB_NAME
        self.user = DB_USER
        self.password = DB_PASSWORD
        self.conn = None

    def get_conn(self):
        self.conn = MySQLdb.connect(host = self.host,
                                    port = self.port,
                                    db = self.name,
                                    user = self.user,
                                    passwd = self.password)

另外,请检查self.conn是否先设置,而不是每次都在get_conn创建新的def get_conn(self): if self.conn is None: self.conn = MySQLdb.connect(host = self.host, port = self.port, db = self.name, user = self.user, passwd = self.password) return self.conn ,如下所示:

get_conn

最后,像这样调用mydbconnobj = DBConnection('localhost',3306,'foouser','foopass','foodbname') mydbconn = mydbconnobj.get_conn() 方法:

{{1}}