-
Notifications
You must be signed in to change notification settings - Fork 0
/
connect_db.py
52 lines (42 loc) · 1.28 KB
/
connect_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
45
46
47
48
49
50
51
52
"""
Script for interactions with database -- dB
"""
import psycopg2
from config import config
# connect to Postgres dB
conn = psycopg2.connect("dbname=suppliers user=postgres password=postgres")
# or can use an ini file, https://www.postgresqltutorial.com/postgresql-python/connect/
###### Useful Functions ######
def connect():
"""
Function:
- Connect to dB
Output:
- success / error message about connection
"""
conn = None
try:
# read connection parameters
params = config()
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
conn = psycopg2.connect(**params)
# create a cursor
cur = conn.cursor()
# execute a statement
print('PostgreSQL database version:')
cur.execute('SELECT version()')
# display the PostgreSQL database server version
db_version = cur.fetchone()
print(db_version)
# close the communication with the PostgreSQL
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')
###### Python Script ######
if __name__ == '__main__':
connect()