4

我正在尝试学习 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 建立与数据库的连接然后获取游标?

4

1 回答 1

6

你还没有self.conn在任何地方定义。您只是设置connget_conn. 在您的构造函数中定义self.conn,然后更新get_conn为 set 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()
于 2012-04-16T22:20:36.373 回答