· 6 years ago · Jun 19, 2019, 10:54 AM
1from datetime import date
2from sqlite3 import *
3
4
5def create_conn():
6 """Create connection to hours.db."""
7 conn = connect("./files/hours.db")
8 return conn
9
10
11def create_table(conn):
12 """Attempt to create sqlite3 table "hours."
13
14 Args:
15 conn (sqlite3.Connection): Connection to hours.db.
16
17 Raises:
18 OperationalError: If table "hours" already exists.
19 """
20 sql = 'CREATE TABLE hours (ID, Date, Times, Hours, Memo)'
21
22 try:
23 conn.execute(sql)
24 except OperationalError:
25 pass
26
27
28def select_all_len(conn):
29 """Select all entries in table "hours."
30
31 Used for ID purposes so that each entry is uniquely identified.
32
33 Args:
34 conn (sqlite3.Connection): Connection to hours.db.
35
36 Returns:
37 int: Number of entries in table "hours."
38
39 Raises:
40 OperationalError: If sql statement was not executed properly.
41 """
42 sql = 'SELECT * FROM hours'
43
44 try:
45 results = conn.execute(sql)
46 except OperationalError:
47 raise
48 else:
49 entries = results.fetchall()
50 return len(entries)
51
52
53def insert_row(conn, num_entries, times, hours, memo):
54 """Insert info into hours.db table "hours."
55
56 Args:
57 conn (sqlite3.Connection): Connection to hours.db.
58 num_entries (int): Total number of entries in table hours.
59 times (str): Hours worked between (eg. 800 - 1600).
60 hours (str): Total number of hours.
61 memo (str): Memo for entry.
62
63 Raises:
64 OperationalError: If sql statement was not executed properly.
65 """
66 sql = 'INSERT INTO hours VALUES ' \
67 '("{ID}", "{Date}", "{Times}", "{Hours}", "{Memo}")'
68 today = date.today()
69
70 try:
71 conn.execute(sql.format(ID=num_entries + 1, Date=today,
72 Times=times, Hours=hours, Memo=memo))
73 except OperationalError:
74 raise
75 else:
76 conn.commit()