Python如何在类中启动和关闭MySQL连接

时间:2016-06-06 02:06:50

标签: python mysql class

我正在尝试创建一个包含所有数据库操作的类。我希望在调用此类时启动MySQL连接,执行它需要执行的任何数据库操作,并在完成后关闭它。

这是我到目前为止所做的:

import MySQLdb

class Database_Test(object):
    def __init__(self, db_local):
        self.db_conn = MySQLdb.connect(**db_local)
        self.db_cursor = self.db_conn.cursor()

    def get_row(self, sql, data = None):
        self.db_cursor.execute(sql)
        self.resultset = self.db_cursor.fetchall()
        self.db_cursor.close()
        return self.resultset

    # Close db connection something like this?
    # db_conn.close()

db_config =  {
            'host':"127.0.0.1",                 # database host
            'port': 3306,                       # port
            'user':"root",                      # username
            'passwd':"admin",                   # password
            'db':"test",                        # database
            'charset':'utf8'                    # charset encoding
            }

sql = "SELECT * FROM mytest LIMIT 10" 

test = Database_Test(db_config)
test.get_row(sql)
print(test)

这就是我得到的:

<__main__.Database_Test object at 0x00774BF0>

不知怎的,这不是我期望得到的,因为我期望从数据库中获取一些记录。

2 个答案:

答案 0 :(得分:2)

您看到的内容是test对象字符串表示,但您打算获取并使用get_row()方法调用的结果:

test = Database_Test(db_config)
resultset = test.get_row(sql)
print(resultset)

答案 1 :(得分:0)

@Alecxe回答是关于你的语句执行的,如果你有关于打开和关闭连接的问题,你可以使用Context Managers魔术方法:

import MySQLdb

class Database_Test(object):
    def __init__(self, db_local):
        self.db_local = db_local
        self.db_conn = None
        self.db_cursor = None

    def __enter__(self):
        # This ensure, whenever an object is created using "with"
        # this magic method is called, where you can create the connection.
        self.db_conn = MySQLdb.connect(**self.db_local)
        self.db_cursor = self.db_conn.cursor()

    def __exit__(self, exception_type, exception_val, trace):
        # once the with block is over, the __exit__ method would be called
        # with that, you close the connnection
        try:
           self.db_cursor.close()
           self.db_conn.close()
        except AttributeError: # isn't closable
           print 'Not closable.'
           return True # exception handled successfully

    def get_row(self, sql, data = None):
        self.db_cursor.execute(sql)
        self.resultset = self.db_cursor.fetchall()
        return self.resultset

db_config =  {
            'host':"127.0.0.1",                 # database host
            'port': 3306,                       # port
            'user':"root",                      # username
            'passwd':"admin",                   # password
            'db':"test",                        # database
            'charset':'utf8'                    # charset encoding
            }


sql = "SELECT * FROM mytest LIMIT 10" 

with Database_Test(db_config) as test:
    resultSet = test.get_row(sql)
    print(resultSet)