-
Notifications
You must be signed in to change notification settings - Fork 0
/
connect_postgresql.py
65 lines (46 loc) · 1.58 KB
/
connect_postgresql.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
57
58
59
60
61
62
63
64
65
from configparser import ConfigParser
import sqlalchemy
import os
def config(filename='credentials.ini', section='postgresql'):
# Change the directory to the folder where the script itself is located
path = os.path.dirname(os.path.abspath(__file__))
os.chdir(path)
# Create a parser
parser = ConfigParser()
# Read config file
parser.read(filename)
# Get section, default to postgresql
db = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
db[param[0].encode('utf-8') ] = param[1].encode('utf-8')
else:
raise Exception('Section {0} not found in the {1} file'.format(section, filename))
return db
def connect():
""" Connect to the PostgreSQL database server """
try:
# Read connection parameters
params = config()
url = 'postgresql://{}:{}@{}:{}/{}'
url = url.format(params['user'], params['password'], params['host'], \
int(params['port']), params['database'])
# Connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
con = sqlalchemy.create_engine(url, client_encoding='utf8')
print('Connected.')
except Exception as error:
print error
return con
if __name__ == '__main__':
conn=connect()
print("\n")
"""
Perform the tasks of your interest
Like importing a PostgreSQL table as a DataFrame
import pandas as pd
df = pd.read_sql_table("table_name",conn)
"""
conn.dispose()
print('Database connection closed.')