-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_sqlite.py
More file actions
45 lines (35 loc) · 1.03 KB
/
test_sqlite.py
File metadata and controls
45 lines (35 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
"""
Example script of how to use the SQLite db.
What it does:
- Connect to db from Path and navigate
- Create example table with id and name.
- Add any value as a name and save changes with .commit()
- Select all from test_table, store in variable and print
How to run:
- From the project root:
python test_sqlite.py
"""
# libraries like sqlite3 and Path
from pathlib import Path
import sqlite3
# find path to database
DB_PATH = Path("db.sqlite3")
# connect to database and navigate with .cursor()
connect = sqlite3.connect(DB_PATH)
db = connect.cursor()
# make an example table with id and name
db.execute("""
CREATE TABLE IF NOT EXISTS test_table (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL
)
""")
# add example row as a name and save changes with .commit()
db.execute("INSERT INTO test_table (name) VALUES (?)", ("example row",))
connect.commit()
# select all from test_table
db.execute("SELECT * FROM test_table")
rows = db.fetchall()
connect.close()
# print the selected rows
print("Rows in test_table:", rows)