-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathdb_connection.py
More file actions
46 lines (34 loc) · 1.23 KB
/
db_connection.py
File metadata and controls
46 lines (34 loc) · 1.23 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
import psycopg2
import psycopg2.extras
def sql_data(sql_query, operation_type, data=None):
try:
user_name = "flupers"
password = "123"
host = "localhost"
database_name = "db_proman"
connect_str = "postgresql://{user_name}:{password}@{host}/{database_name}".format(
user_name=user_name,
password=password,
host=host,
database_name=database_name
)
print("Connection string: " + connect_str)
connection = psycopg2.connect(connect_str)
connection.autocommit = True
cursor = connection.cursor()
if operation_type == "read":
cursor = connection.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cursor.execute(sql_query, data)
data = cursor.fetchall()
return data
elif operation_type == "write":
cursor.execute(sql_query, data)
else:
cursor.execute(sql_query, data)
cursor.close()
except psycopg2.DatabaseError as exception:
print(exception)
finally:
# checks first whether the connection has been created successfully
if 'connection' in locals():
connection.close()