sqlite3/python dumb question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bigturtle
    New Member
    • Apr 2007
    • 19

    sqlite3/python dumb question

    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":

    Code:
        conn = sqlite3.connect("../data/mydata")
        db = conn.cursor()
        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
    New Member
    • Apr 2007
    • 19

    #2
    Got it myself

    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

    Code:
    db.execute( "SELECT COUNT(*) FROM thefile" )
    Result = db.fetchall()
    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?

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      bigturtle,

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

      -BV

      Comment

      Working...