【问题标题】:Python MySQLdb "with" syntax and DictCursorPython MySQLdb "with" 语法和 DictCursor
【发布时间】:2013-01-30 13:54:51
【问题描述】:

我正在尝试将 DictCursorwith 块一起使用。我认为通过使用:

with MySQLdb.connect(...) as c:

c 将是一个连接对象,因为这就是 connect() 返回的内容。但很可惜,事实并非如此!突然之间,c 变成了一个光标!虽然这通常很方便,但我真的很喜欢使用DictCursor - 这根本不是这样设计的吗?将 DictCursor 包含为“作用域对象”会导致错误(__exit__ 未定义)

【问题讨论】:

标签: python mysql-python


【解决方案1】:

c 是一个游标,因为这是上下文管理器的 __enter__ 方法返回的内容。
如果你浏览Mysqldb的源码,你可以在line 245 of connections.py看到:

def __enter__(self): return self.cursor()

至于DictCursor,不支持上下文管理。

【讨论】:

  • 我有点困惑 - with MySQLdb.connect(...) as c: 不起作用吗?还是我错过了什么?至少它不会引发异常!
  • 是的,它可以工作,但正如我所说,它旨在返回一个光标。
【解决方案2】:

根据这里line 254 of connections.py中MySQLdb中Connection的定义,Connection.cursor()会返回一个Connection.cursorclass的实例:

def cursor(self, cursorclass=None):
    """
    Create a cursor on which queries may be performed. The
    optional cursorclass parameter is used to create the
    Cursor. By default, self.cursorclass=cursors.Cursor is
    used.
    """
    return (cursorclass or self.cursorclass)(self)

所以,我猜如果您使用参数“cursorclass”初始化连接,并将其设置为 MySQLdb.cursors.DictCursor,例如:

dbconn = MySQLdb.connect(cursorclass=MySQLdb.cursors.DictCursor)

什么时候来

def __enter__(self):
    if self.get_autocommit():
        self.query("BEGIN")
    return self.cursor()

它将返回一个字典光标。

【讨论】:

    【解决方案3】:

    我使用 sqlalchemy 修复原始 sql

    if self.engine.url.drivername == 'mysql+pymysql':
        from pymysql.cursors import SSDictCursor
        connection = self.engine.raw_connection()
        cursor = connection.cursor(cursor=SSDictCursor)
    elif self.engine.url.drivername == 'mysql+mysqldb':
        import MySQLdb.cursors
        connection = self.engine.raw_connection()
        cursor = connection.cursor(cursorclass=MySQLdb.cursors.DictCursor)
    else:
        connection = self.engine.raw_connection()
        cursor = connection.cursor()
    

    或创建连接时使用

    connect_args=dict(cursorclass=MySQLdb.cursors.DictCursor)
    

    【讨论】:

      猜你喜欢
      • 2014-05-11
      • 1970-01-01
      • 1970-01-01
      • 2012-03-12
      • 2011-08-02
      • 2013-12-15
      • 1970-01-01
      相关资源
      最近更新 更多