-
Notifications
You must be signed in to change notification settings - Fork 0
/
hw4db.py
65 lines (44 loc) · 1.48 KB
/
hw4db.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
import psycopg2
def create():
cur.execute(
'CREATE TABLE books (book_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,name VARCHAR(255) NOT NULL,author VARCHAR(255) NOT NULL,publisher VARCHAR(255) NOT NULL,price DECIMAL(10,2) NOT NULL,available BOOLEAN NOT NULL DEFAULT true)')
conn.commit()
def insert(data):
cur.execute('INSERT INTO books (name, author,publisher,price) VALUES (%s,%s ,%s,%s);', data)
conn.commit()
def read(query):
cur.execute(query)
rows = cur.fetchall()
return rows
def update_available(data):
cur.execute('UPDATE books SET available = false WHERE book_id = %s', data)
conn.commit()
def delete(data):
cur.execute('DELETE FROM books WHERE book_id = %s', data)
conn.commit()
if __name__ == '__main__':
conn = psycopg2.connect(
dbname="postgres",
user="postgres",
password="admin",
host="localhost",
port="5432"
)
cur = conn.cursor()
create()
data = ('harrypotter', 'J. K. Rowling', 'Bloomsbury', 3.8)
insert(data)
data = ('The Great Gatsby', 'F. Scott Fitzgerald', 'Scribner', 12.99)
insert(data)
query = 'SELECT * FROM books'
print(read(query))
data = (1,)
update_available(data)
query = 'SELECT * FROM books'
print(read(query))
data = (2,)
delete(data)
query = 'SELECT * FROM books'
print(read(query))
cur.close()
conn.close()