【问题标题】:Python how to initiate and close a MySQL connection inside a classPython如何在类中启动和关闭MySQL连接
【发布时间】:2016-06-06 02:06:49
【问题描述】:

我正在尝试创建一个包含所有数据库操作的类。我想在调用此类时启动 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>

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

【问题讨论】:

  • 不要忘记建立连接比使用现有连接要昂贵得多。大多数数据库系统鼓励使用活动连接池,您可以从池中获取连接,使用它,并在完成后将其释放回池中。

标签: python mysql class


【解决方案1】:

@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()
        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)

【讨论】:

  • 你需要从get_row()中删除self.db_cursor_close()
  • @Nicarus 是的,请注意。 :)
  • 上述我都试过了,但是遇到了'NoneType' object has no attribute ___method_name_here___ 解决了在__enter__(self)返回selfstackoverflow.com/questions/5093382/…
【解决方案2】:

您看到打印的是test 对象字符串表示,但您的意思是获取和使用get_row() 方法调用的结果:

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

【讨论】:

  • 那真是我的菜鸟。我没有意识到我正在打印字符串表示。无论如何,使用后如何关闭类内的连接?
猜你喜欢
  • 1970-01-01
  • 2015-11-29
  • 1970-01-01
  • 2021-09-03
  • 2015-03-08
  • 2013-03-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多