-
Notifications
You must be signed in to change notification settings - Fork 0
/
init_db.py
42 lines (31 loc) · 1.06 KB
/
init_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
import os
import psycopg2
# username = os.environ["DB_USERNAME"]
# password = os.environ["DB_PASSWORD"]
username = os.environ["DB_USERNAME"]
password = os.environ["DB_PASSWORD"]
conn = psycopg2.connect(host="localhost", database="flask_db", user=username, password=password)
# Open a cursor to perform database operations
cur = conn.cursor()
# Execute a command: this creates a new table
cur.execute("DROP TABLE IF EXISTS books;")
cur.execute(
"CREATE TABLE books (id serial PRIMARY KEY,"
"title varchar (150) NOT NULL,"
"author varchar (50) NOT NULL,"
"pages_num integer NOT NULL,"
"review text,"
"date_added date DEFAULT CURRENT_TIMESTAMP);"
)
# Insert data into the table
cur.execute(
"INSERT INTO books (title, author, pages_num, review) VALUES (%s, %s, %s, %s)",
("A Tale of Two Cities", "Charles Dickens", 489, "A great classic!"),
)
cur.execute(
"INSERT INTO books (title, author, pages_num, review) VALUES (%s, %s, %s, %s)",
("Anna Karenina", "Leo Tolstoy", 864, "Another great classic!"),
)
conn.commit()
cur.close()
conn.close()