SQLite Save to File
Save the Database in a File
So far, the examples have used ":memory:", and the data was gone when the program ended.
To keep the data, give connect() a file name. The data is saved in that file, and is still there the next time you run the program:
Example
Save the players table in a file named game.db:
import sqlite3
con = sqlite3.connect("game.db")
cur = con.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS players
(name TEXT, score INTEGER)
""")
cur.execute("""
INSERT INTO players
VALUES ('Emil', 120)
""")
con.commit()
cur.execute("SELECT * FROM players")
print(cur.fetchall())
con.close()
Run Example »
The second time, the row from the first time is still there, and one more row is added.
Run the Examples on Your Computer
The examples on this page save a file, so they work best on your own computer:
- Save the code in a file, for example
game.py - Run the file from the command line:
python game.py - Run it again, and see that the data is still there
When you click "Run Example", you will see the code together with the result. For the first example, you see the result from the first and the second time it runs.
Example Explained
- The first time, the file game.db does not exist, so
connect()creates a new, empty database file. CREATE TABLE IF NOT EXISTScreates the table the first time. The next times, the table is already in the file, so nothing happens.- Each time the program runs, it inserts one more row, so the rows add up.
con.commit()saves the new row in the file.con.close()closes the connection to the database.
Tip: To start over with an empty database, delete the game.db file.
Read the Data in Another Program
The data is in the file, so another program can open it too. This program only reads the players table:
Example
Read the players table from game.db:
import sqlite3
con = sqlite3.connect("game.db")
cur = con.cursor()
cur.execute("SELECT * FROM players")
print(cur.fetchall())
con.close()
Run Example »
If you have run the first example twice, this program prints both rows.
Remember to Commit
The changes are saved in the file only when you call con.commit(). If the program ends without commit(), the changes are lost.
con.close() does not commit for you. Call commit() first, and then close().
Close the Connection
When you are done with the database, call con.close(). Python also closes the connection when the program ends, but it is a good habit to close it yourself.
Where is the File?
The file is created in the current working directory. That is usually the folder you were in when you started the program.
To put the file somewhere else, write the full path to the file, for example "C:/games/game.db" on Windows.