-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathdb.py
115 lines (105 loc) · 2.82 KB
/
db.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import sqlite3, random, datetime
from models import Book
def getNewId():
return random.getrandbits(28)
books = [
# {
# 'available': True,
# 'title': 'Don Quixote',
# 'timestamp': datetime.datetime.now()
# },
{
'available': True,
'title': 'A Tale of Two Cities',
'timestamp': datetime.datetime.now()
},
{
'available': True,
'title': 'The Lord of the Rings',
'timestamp': datetime.datetime.now()
},
{
'available': True,
'title': 'The Little Prince',
'timestamp': datetime.datetime.now()
},
{
'available': True,
'title': "Harry Potter and the Sorcerer's Stone",
'timestamp': datetime.datetime.now()
},
{
'available': True,
'title': 'And Then There Were None',
'timestamp': datetime.datetime.now()
},
{
'available': True,
'title': 'The Dream of the Red Table',
'timestamp': datetime.datetime.now()
},
{
'available': True,
'title': 'The Hobbit',
'timestamp': datetime.datetime.now()
},
{
'available': True,
'title': 'The Lion, the Witch and the Wardrobe',
'timestamp': datetime.datetime.now()
},
{
'available': True,
'title': 'The Da Vinci Code',
'timestamp': datetime.datetime.now()
},
]
def connect():
conn = sqlite3.connect('books.db')
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS books (id INTEGER PRIMARY KEY, available BOOLEAN, title TEXT, timestamp TEXT)")
conn.commit()
conn.close()
for i in books:
bk = Book(getNewId(), i['available'], i['title'], i['timestamp'])
insert(bk)
def insert(book):
conn = sqlite3.connect('books.db')
cur = conn.cursor()
cur.execute("INSERT INTO books VALUES (?,?,?,?)", (
book.id,
book.available,
book.title,
book.timestamp
))
conn.commit()
conn.close()
def view():
conn = sqlite3.connect('books.db')
cur = conn.cursor()
cur.execute("SELECT * FROM books")
rows = cur.fetchall()
books = []
for i in rows:
book = Book(i[0], True if i[1] == 1 else False, i[2], i[3])
books.append(book)
conn.close()
return books
def update(book):
conn = sqlite3.connect('books.db')
cur = conn.cursor()
cur.execute("UPDATE books SET available=?, title=? WHERE id=?", (book.available, book.title, book.id))
conn.commit()
conn.close()
def delete(theId):
conn = sqlite3.connect('books.db')
cur = conn.cursor()
cur.execute("DELETE FROM books WHERE id=?", (theId,))
conn.commit()
conn.close()
def deleteAll():
conn = sqlite3.connect('books.db')
cur = conn.cursor()
cur.execute("DELETE FROM books")
conn.commit()
conn.close()