forked from kgex/kgfoss
-
Notifications
You must be signed in to change notification settings - Fork 0
/
init_db.py
44 lines (34 loc) · 1.03 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
43
44
import os
import psycopg2
from dotenv import load_dotenv
load_dotenv()
conn = psycopg2.connect(
host=os.environ["DB_URL"],
database=os.environ["DB_DB"],
user=os.environ["DB_USERNAME"],
password=os.environ["DB_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()