Home » Mysql » Python db-api: fetchone vs fetchmany vs fetchall

Python db-api: fetchone vs fetchmany vs fetchall

Posted by: admin November 1, 2017 Leave a comment

Questions:

I just had a discussion today with some coworkers about python’s db-api fetchone vs fetchmany vs fetchall.

I’m sure the use case for each of these is dependent on the implementation of the db-api that I’m using, but in general what are the use cases for fetchone vs fetchmany vs fetchall?

In other words are the following equivalent? or is there one of these that is preferred over the others? and if so in which situations?

cursor.execute("SELECT id, name FROM `table`")
for i in xrange(cursor.rowcount):
    id, name = cursor.fetchone()
    print id, name


cursor.execute("SELECT id, name FROM `table`")
result = cursor.fetchmany()
while result:
    for id, name in result:
        print id, name
    result = cursor.fetchmany()


cursor.execute("SELECT id, name FROM `table`")
for id, name in cursor.fetchall():
    print id, name
Answers:

I think it indeed depends on the implementation, but you can get an idea of the differences by looking into MySQLdb sources. Depending on the options, mysqldb fetch* keep the current set of rows in memory or server side, so fetchmany vs fetchone has some flexibility here to know what to keep in (python’s) memory and what to keep db server side.

PEP 249 does not give much detail, so I guess this is to optimize things depending on the database while exact semantics are implementation-defined.

Questions:
Answers:

These are implementation specific.

  • fetchall

Will get all the results from the table. This will work better when size of the table is small. If the table size is bigger, fetchall will fail in those cases.

Will use most of the memory.

Will cause some issues will can occur if the queries is done on network.

  • fetchmany

fetchmany will get only required number of results. You can yield the results and process. Simple Snippet of implementation of fetchmany.

   while True:
    results = cursor.fetchmany(arraysize)
    if not results:
        break
    for result in results:
        yield result