-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.py
70 lines (48 loc) · 1.24 KB
/
database.py
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import sqlite3
from prettytable import from_db_cursor
def get_connection(db_name):
con = sqlite3.connect(db_name)
con.row_factory = sqlite3.Row
return con
def create_table(con):
sql_create_primes_table = """
CREATE TABLE IF NOT EXISTS primes (
id integer PRIMARY KEY,
primes integer UNIQUE,
creation_date text NOT NULL);
"""
with con:
con.execute(sql_create_primes_table)
rows = get_all_primes(con)
def insert_rows(con, rows):
sql_insert_primes = """
INSERT INTO primes(primes, creation_date) VALUES (?, DATETIME('now')
);"""
with con:
try:
con.executemany(sql_insert_primes, rows)
except sqlite3.IntegrityError:
return 'Line already exists.'
rows = get_all_primes(con)
def get_all_primes(con):
sql_select_all_primes = """
SELECT * FROM primes;
"""
return con.execute(sql_select_all_primes)
def print_table(rows):
table = from_db_cursor(rows)
print(table)
# ----------------------- Test ---------------------------
def test_db_creation():
con = get_connection(':memory:')
create_table(con)
rows = [
(2,),
(3,),
(5,),
]
insert_rows(con, rows)
rows = get_all_primes(con)
print_table(rows)
con.close()
# test_db_creation()