Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is sqlite3 fetchall necessary?

Tags:

python

sql

sqlite

I just started using sqlite3 with python . I would like to know the difference between :

cursor = db.execute("SELECT customer FROM table")
    for row in cursor:
              print row[0]

and

cursor = db.execute("SELECT customer FROM table")
    for row in cursor.fetchall():
              print row[0]

Except that cursor is <type 'sqlite3.Cursor'> and cursor.fetchall() is <type 'list'>, both of them have the same result .

Is there a difference, a preference or specific cases where one is more preferred than the other ?

like image 256
4m1nh4j1 Avatar asked Jan 24 '14 14:01

4m1nh4j1


People also ask

What is Fetchall in sqlite3?

The sqlite3. Cursor class provides three methods namely fetchall(), fetchmany() and, fetchone() where, The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones).

What is the use of Fetchall method?

fetchall() Method. The method fetches all (or all remaining) rows of a query result set and returns a list of tuples. If no more rows are available, it returns an empty list. You must fetch all rows for the current query before executing new statements using the same connection.

What does Fetchall return?

fetchall() fetches all the rows of a query result. It returns all the rows as a list of tuples. An empty list is returned if there is no record to fetch. cursor.

What is the use of cursor in sqlite3?

The sqlite3. Cursor class is an instance using which you can invoke methods that execute SQLite statements, fetch data from the result sets of the queries. You can create Cursor object using the cursor() method of the Connection object/class.


1 Answers

fetchall() reads all records into memory, and then returns that list.

When iterating over the cursor itself, rows are read only when needed. This is more efficient when you have much data and can handle the rows one by one.

like image 101
CL. Avatar answered Oct 13 '22 00:10

CL.