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])
- Run above Python files in the same folder as the bookshop.db database, and make sure you get no error messages.
- 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
- How could I modify the books_showone.py code above, to show tuple number 3 from the
result
list? - 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. - 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.
Core Activities:
Extension Activities: