Connecting Tech Pros Worldwide Forums | Help | Site Map

sqlite3/python dumb question

bigturtle's Avatar
Newbie
 
Join Date: Apr 2007
Location: Neijiang, Sichuan, China
Posts: 19
#1: Dec 18 '08
I'm trying to do some database stuff in Python 2.6 with sqlite3, and am having trouble understanding the basics of the interface between the two. I am able to create database files and retrieve records, but some other commands are mysterious.

Here's a snippet where I'm trying to retrieve the number of records in file "thefile", located in database "mydata" in sister folder "data":

Expand|Select|Wrap|Line Numbers
  1.     conn = sqlite3.connect("../data/mydata")
  2.     db = conn.cursor()
  3.     NRecs = db.execute( "SELECT COUNT(*) FROM thefile" ) 
OK, where do I find the output of the SELECT command? NRecs is a "cursor" object and the number of records is not stored there in any reasonable way I can see. I know this is baby stuff, but without the answer I can't work properly. Thanks for your help.

bigturtle's Avatar
Newbie
 
Join Date: Apr 2007
Location: Neijiang, Sichuan, China
Posts: 19
#2: Dec 19 '08

re: sqlite3/python dumb question


Figured it out on my own, thanks to Peyton McCulloch's tutorial at
Using SQLite in Python.

You retrieve the results of cursor.execute() using the fetchall() or fetchmany() method from the cursor class. So rewriting the last line of the snippet above gives

Expand|Select|Wrap|Line Numbers
  1. db.execute( "SELECT COUNT(*) FROM thefile" )
  2. Result = db.fetchall()
  3. NRecs = Result[0][0]
In general, fetchall() returns a list of tuples. In this case, if there are, say, 408 records in the file, Result is [(408,)] so the # of records is the first element of the first tuple.

Was that obvious?
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,563
#3: Dec 19 '08

re: sqlite3/python dumb question


bigturtle,

It's not obvious to me. I now know more about SQLite than I did. Thanks for sharing.

-BV
Reply

Tags
python, select, sqlite, sqlite3