Connecting to Restaurant Database
connect1.py
import sqlite3 #Make sure restaurant.db is saved to #the same folder as this Python file. #If the database file can't be found, #it will be created instead: db = sqlite3.connect('restaurant.db') print("database connection opened.") db.close() print("database connection closed.")
connect2.py
import sqlite3 db = sqlite3.connect('restaurant.db') #A database cursor "points" to the rows taken from a query result: cursor = db.cursor() cursor.execute("SELECT * FROM menu") #fetchall() will give you the entire result set client-side. #this will be in the form of a list of tuples, with each tuple #corresponding to one record from the result set: result = cursor.fetchall() print(result) db.close()
connect3.py
import sqlite3 #with error checking, incase #something goes pear shaped, #it is good to find out why: try: db = sqlite3.connect('restaurant.db') cursor = db.cursor() cursor.execute("SELECT * FROM menu") result = cursor.fetchall() print(result) except Exception as error_msg: print("An error occured:", error_msg) finally: db.close()
What happens when you change the querystring in the final Python example to "SELECT * FROM table_that_doesnt_exist"?