代码之家  ›  专栏  ›  技术社区  ›  Sylvain

如何有效地使用mysqldb sscursor?

  •  29
  • Sylvain  · 技术社区  · 15 年前

    我必须处理一个大的结果集(可能是数十万行,有时更多)。
    不幸的是,它们需要一次全部取回(启动时)。

    我试图用尽可能少的内存来做到这一点。
    通过观察,我发现 SSCursor 可能是我要找的,但我仍然不知道如何确切地使用它们。

    正在做 fetchall() 从一个基本光标或一个相同的SScursor(在内存使用方面)?
    我能一行一行(或几行一行)地“流”出来吗?如果可以的话,
    最好的方法是什么?

    3 回复  |  直到 7 年前
        1
  •  29
  •   unutbu    15 年前

    我同意Otto Allmendinger的回答,但是为了明确Denis Otkidach的评论,下面是不使用Otto的fetch()函数的情况下如何迭代结果:

    import MySQLdb.cursors
    connection=MySQLdb.connect(
        host="thehost",user="theuser",
        passwd="thepassword",db="thedb",
        cursorclass = MySQLdb.cursors.SSCursor)
    cursor=connection.cursor()
    cursor.execute(query)
    for row in cursor:
        print(row)
    
        2
  •  10
  •   Otto Allmendinger    15 年前

    在获取大结果集时一定要使用sscursor。当我遇到类似的问题时,这对我有很大的影响。您可以这样使用它:

    import MySQLdb
    import MySQLdb.cursors
    
    connection = MySQLdb.connect(
            host=host, port=port, user=username, passwd=password, db=database, 
            cursorclass=MySQLdb.cursors.SSCursor) # put the cursorclass here
    cursor = connection.cursor()
    

    现在,您可以使用 cursor.execute() 并将光标用作迭代器。

    编辑 :删除了不必要的本地迭代器,谢谢丹尼斯!

        3
  •  0
  •   Yuda Prawira David Dehghan    7 年前

    或者,您可以使用 SSCursor 在连接对象之外(当您已经定义了连接并且不希望所有连接都使用时,这一点非常重要 SS游标 作为一个草书类)。

    import MySQLdb
    from MySQLdb.cursors import SSCursor # or you can use SSDictCursor
    
    connection = MySQLdb.connect(
            host=host, port=port, user=username, passwd=password, db=database)
    cursor = SSCursor(connection)
    cursor.execute(query)
    for row in cursor:
        print(row)