forked from COMP491-Team-Education/Demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin_offline.py
110 lines (87 loc) · 2.62 KB
/
plugin_offline.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
import psycopg2
def connect(host, db, username, password):
try:
# Establish a connection
conn = psycopg2.connect(
host= host,
database= db,
user= username,
password= password
)
# Create a cursor object to execute queries
cur = conn.cursor()
except:
print(error)
# GET: Fetch a book by title
def get_book(book_title, cur):
# query
cur.execute(f'''SELECT id, title, author, picture FROM Books WHERE title = {book_title}''')
# Fetch the result
result = cur.fetchall()
if result:
# Convert the row into a dictionary
book = {
"id": result[0],
"title": result[1],
"author": result[2],
"picture": result[3],
}
return book
else:
print("error: Book not found")
# GET: Fetch a book by author
def get_book(author, cur):
# query
cur.execute(f'''SELECT id, title, author, picture FROM Books WHERE author = {author}''')
# Fetch the result
result = cur.fetchall()
if result:
# Convert the row into a dictionary
book = {
"id": result[0],
"title": result[1],
"author": result[2],
"picture": result[3],
}
return book
else:
print("error: Book not found")
# POST: Add a new book
def add_book(title, author, picture, cur):
try:
# Query to insert a new book
cur.execute(f'''
INSERT INTO Books (title, author, picture)
VALUES {title, author, picture}
''')
# Commit the transaction
cur.connection.commit()
print("Book added successfully")
return True
except Exception as e:
print(f"Error adding book: {str(e)}")
return False
# DELETE: Remove a book by its ID
def remove_book(book_name, cur):
try:
# Query to delete the book
cur.execute(f'''
DELETE FROM Books
WHERE title = {book_name}
''')
# Check if any row was affected
if cur.rowcount > 0:
# Commit the transaction
cur.connection.commit()
print("Book removed successfully")
return True
else:
print("Error: Book not found")
return False
except Exception as e:
print(f"Error removing book: {str(e)}")
return False
#close the connection
def close(curr):
cur.close()
conn.close()