Python Practice › SQLite Programs › Program 14
Use a database file
Write a Python program that saves data to a .db file and reads it back with a new connection.
Output
[('pen', 10.0)] TrueApproach
- Connect to a file name; close and reconnect.
Solution
import osimport sqlite3 if os.path.exists("shop.db"): os.remove("shop.db")with sqlite3.connect("shop.db") as conn: conn.execute("CREATE TABLE items (name TEXT, price REAL)") conn.execute("INSERT INTO items VALUES ('pen', 10)")conn.close() conn = sqlite3.connect("shop.db")print(conn.execute("SELECT * FROM items").fetchall(), os.path.getsize("shop.db") > 0)conn.close()Output
[('pen', 10.0)] TrueLine by line
Lines 6-8
The with block commits the insert; close() releases the file.
Learn the concept
New to this topic? Read the lesson, then come back.