0%

When a File Is No Longer Enough · practice

Close and Reopen the Same Database

What happens to stored data after connection.close()?

An in-memory database disappears with its connection, so it cannot answer that question. This time, SQLite will use a database file. We will store a short piece of text, close the connection, open the same file again, and try to read the text back.

Write, close, and reopen

The first part of reopen_and_read() is already complete:

first_connection = sqlite3.connect(database_path)
run_query.initialize_marker(first_connection, marker)
first_connection.close()

database_path tells SQLite which file to open. The first connection writes the in marker, then closes.

Pause before you continue. If a second call to sqlite3.connect() uses that same path, do you expect it to read the marker or find an empty database?

Open persistence.py and find the missing second connection:

second_connection = None

Replace None with a new connection to database_path. Keep the rest of the as it is, then press Run and find the == persistence.py == heading.

If the marker appears after reopening, compare what changed with what stayed the same. first_connection is closed. second_connection is a different Python . The path is unchanged, so both connections reach the same database file.

Opening a connection, using it, and closing it is the connection’s lifecycle. The data outliving the connection that wrote it is file durability. You have now seen both happen.

The site removes this temporary database file after Run finishes. On your own computer, a database file remains until you or your program remove it.

What does it prove when the second connection reads the first connection's marker?

You closed one connection completely and still recovered its data through another. Next, follow the familiar question “What can people borrow?” from Python to the stored rows and back.

Task

In persistence.py, replace None with a new connection to database_path.

Keep first_connection and second_connection separate, close each one after its work, and return the read through the second connection.