Copy cursor object in Python

I am working on Trac-Plugin ...

To get my data, I create a cursor object and get a table of results as follows:

 db = self.env.get_db_cnx()
 cursor = db.cursor()
 cursor.execute("SELECT...") 

Now the result is used in three different functions. My problem is that the cursor clears during the loop for the first time (for example, it says http://packages.python.org/psycopg2/cursor.html )

Then I tried to copy the cursor object, but that also failed. the function copy(cursor)seems to have problems with a large dataset, and the function deepcopy(cursor)fails anyway (according to this error http://bugs.python.org/issue1515 ).

How can I solve this problem?

+3
source share
2 answers

:

results = list(cursor)

. , .

, .

, 9000 , - , , , list.

+9

, :

def lazy_execute(sql, cursor=cursor):
    results = []
    cursor.execute(sql)
    def fetch():
        if results:
            for r in results:
                yield r
            raise StopIteration()
        else:
            for r in cursor:
                results.append(r)
                yield r
            raise StopIteration()

    return fetch

, , . :

results = lazy_execute(my_sql):
for r in results():
    "do something with r"

, , , , , .

, , , , , , , .

.

0

All Articles