By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,742 Members | 1,206 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,742 IT Pros & Developers. It's quick & easy.

sqlite3/python dumb question

P: 19
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.
Dec 18 '08 #1
Share this Question
Share on Google+
2 Replies

P: 19
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?
Dec 19 '08 #2

Expert Mod 2.5K+
P: 2,851

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

Dec 19 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.