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

Cry*_*sie 2 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)
Run Code Online (Sandbox Code Playgroud)

这就是我得到的:

<__main__.Database_Test object at 0x00774BF0>
Run Code Online (Sandbox Code Playgroud)

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

Nag*_*tri 6

@Alecxe 答案是关于您的语句执行,如果您对打开和关闭连接有疑问,您可以使用上下文管理器魔术方法:

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()
        return self

    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)
Run Code Online (Sandbox Code Playgroud)

  • 我已经尝试过上述方法,但遇到“NoneType”对象没有属性 ___method_name_here___` 通过在 `__enter__(self)` 中返回 `self` 解决了 /sf/ask/356536771/ -使用上下文管理器 (2认同)