External Exam Download Resources Web Applications Games Recycle Bin

Displaying Bookshop Data Rows

books.py

import sqlite3
db = sqlite3.connect('bookshop.db')
result = db.cursor().execute("SELECT * FROM books").fetchall()
db.close()

books_showall.py

import sqlite3
db = sqlite3.connect('bookshop.db')
result = db.cursor().execute("SELECT * FROM books").fetchall()
db.close()

print(result)

books_showone.py

import sqlite3
db = sqlite3.connect('bookshop.db')
result = db.cursor().execute("SELECT * FROM books").fetchall()
db.close()

print(result[0]) #shows tuple number 0

books_showtwo.py

import sqlite3
db = sqlite3.connect('bookshop.db')
result = db.cursor().execute("SELECT * FROM books").fetchall()
db.close()

print(result[0])
print(result[1])

    Core Activities:

  1. Run above Python files in the same folder as the bookshop.db database, and make sure you get no error messages.
  2. Explain what the difference is in output (i.e. what is the difference between what is printed to the console window) between the files above:
    • books_showall.py
    • books_showone.py
    • books_showtwo.py
  3. How could I modify the books_showone.py code above, to show tuple number 3 from the result list?
  4. Extension Activities:

  5. The variable result in the above code is a list of tuples, as is the case here:
    result = [("a","b","c"),("d","e","f")]
    print(result[0])

    Modify this last piece of code to print ('d', 'e', 'f') to the console window.
  6. Use random number code to generate a random integer in the range of 0 to 12 (inclusive). Use that random number to display a random book tuple from the result list.