Page 205 -
P. 205

all in the details


           The code remains the same; it's                                    I asked our technical
                                                                               people and they told me we
           the function that changes                                           use SQLite3... whatever
                                                                              that is. They also gave me
           Your program expects the find_details() function                    some code for you to amend...
           to return a hash representing the surfer’s details. Rather         they told me you‛d know
           than the function searching the file for the data, it needs         what to do with it, which is
           to search the TVN database, convert what the database              just as well because it‛s all
           provides to a hash, and then return the hash to the                 gobbledygook to me!
           calling code.

           All you need to know is which database system TVN
           is using and how to access it from your function.
           Let’s base your code on TVN’s code.









                    Ready Bake
                    Code     Here‛s the TVN code:


          Import the standard
          SQLite3 library     import sqlite3
          and connect to the
          data in the database   db = sqlite3.connect("surfersDB.sdb")
          file (which you can
           download from this   db.row_factory = sqlite3.Row         Grab all the surfer
           book's website).   cursor = db.cursor()                   data from the
                              cursor.execute("select * from surfers") database, assigning
            Process each of   rows = cursor.fetchall()               the data to a variable
            the rows...                                              called “rows”.
                              for row in rows:
            ...looking for a       if row['id'] == 104:
            surfer who has an           print("ID is " + str(row['id']))    Print out
             ID of 104.               print("Name is " + row['name'])       some of the
                                                                            data (if we
                                      print("Board-type is " + row['board'])
                                                                            have a match).
                              cursor.close()
                                              Tidy up after yourself (always a good idea).




                                      It is possible to improve the efficiency and power of this code if you know a

                                      we strongly recommend “Head First SQL” to those who want to learn more.
           170    Chapter 5           little bit about SQL. We are deliberately avoiding improving TVN's SQL. However,
   200   201   202   203   204   205   206   207   208   209   210