-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase_com.py
56 lines (50 loc) · 1.52 KB
/
database_com.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
import psycopg2
from psycopg2 import OperationalError
def create_connection(db_name, db_user, db_password, db_host, db_port):
connection = None
try:
connection = psycopg2.connect(
database=db_name,
user=db_user,
password=db_password,
host=db_host,
port=db_port,
)
print("Connection to PostgreSQL DB successful")
except OperationalError as e:
print(f"The error '{e}' occurred")
return connection
def create_table(connection):
connection.autocommit = True
cursor = connection.cursor()
create_users_table = """
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
count INTEGER,
date TEXT
)
"""
try:
cursor.execute(create_users_table)
print("Query executed successfully")
except OperationalError as e:
print(f"The error '{e}' occurred")
def insert_exec(connection, query, values):
connection.autocommit = True
cursor = connection.cursor()
try:
cursor.execute(query, values)
print("Query executed successfully")
except OperationalError as e:
print(f"The error '{e}' occurred")
def execute_read_query(connection, query, *par):
connection.autocommit = True
cursor = connection.cursor()
result = None
try:
cursor.execute(query, tuple(par))
result = cursor.fetchall()
return result
except OperationalError as e:
print(f"The error '{e}' occurred")