Python Practice › SQLite Programs › Program 14

Use a database file

EasySQLite Programs · 14 of 20

Write a Python program that saves data to a .db file and reads it back with a new connection.

Advertisement
Output
[('pen', 10.0)] True

Approach

  1. Connect to a file name; close and reconnect.

Solution

Python
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)] True

Line 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.

More sqlite programs

← All 20 SQLite Programs

Leave a Comment