-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_database.py
More file actions
55 lines (48 loc) · 1.57 KB
/
test_database.py
File metadata and controls
55 lines (48 loc) · 1.57 KB
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
import psycopg2
from config import config
def insert_user_message(user_message: str):
""" insert a new user into the message table """
sql = """INSERT INTO messages(user_message)
VALUES(%s) RETURNING user_id;"""
conn = None
user_id = None
try:
# read database configuration
params = config()
# connect to the PostgreSQL database
conn = psycopg2.connect(**params)
# create a new cursor
cur = conn.cursor()
# execute the INSERT statement
cur.execute(sql, (user_message,))
# get the generated id back
user_id = cur.fetchone()[0]
# commit the changes to the database
conn.commit()
# close communication with the database
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
return 'Loading'
def get_message():
""" query data from the messages table """
conn = None
try:
params = config()
conn = psycopg2.connect(**params)
cur = conn.cursor()
cur.execute("SELECT user_id, user_message FROM messages ORDER BY user_message")
print("Number of messages: ", cur.rowcount)
row = cur.fetchone()
while row is not None:
print(row)
row = cur.fetchone()
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()