-
Notifications
You must be signed in to change notification settings - Fork 0
/
db_connector.py
95 lines (72 loc) · 3.52 KB
/
db_connector.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import psycopg2
class db_connector:
def write_into_db_with_return(sql,values):
conn = None
try:
connection = psycopg2.connect(user = "postgres",
password = "",
host = "",
port = "5432",
database = "postgres")
# connection = psycopg2.connect(user = "postgres",
# password = "",
# host = "127.0.0.1",
# port = "5432",
# database = "postgres")
cursor = connection.cursor()
# Print PostgreSQL version
cursor.execute(sql,values)
connection.commit()
# get id of entry
# print('Print: ' + cursor.fetchone()[0])
id = cursor.fetchone()[0]
except (Exception, psycopg2.Error) as error :
print ("Error while connecting to PostgreSQL", error)
finally:
#closing database connection.
if(connection is not None):
cursor.close()
connection.close()
# print("PostgreSQL connection is closed")
return id
def write_into_db(sql,values):
conn = None
try:
# connection = psycopg2.connect(user = "postgres",
# password = "2909",
# host = "127.0.0.1",
# port = "5432",
# database = "postgres")
connection = psycopg2.connect(user = "postgres",
password = "1234password",
host = "database-1.c0dgpcuvhe44.eu-central-1.rds.amazonaws.com",
port = "5432",
database = "postgres")
cursor = connection.cursor()
# Print PostgreSQL version
cursor.execute(sql,values)
connection.commit()
# get id of entry
# print('Print: ' + cursor.fetchone()[0])
except (Exception, psycopg2.Error) as error :
# pass
print ("Error while connecting to PostgreSQL", error)
finally:
#closing database connection.
if(connection is not None):
cursor.close()
connection.close()
# print("PostgreSQL connection is closed")
def write_city(name, coordinates):
sql = "INSERT INTO city(city_name, coordinates ) VALUES (%s,point%s) RETURNING id"
city_id = db_connector.write_into_db_with_return(sql, (name, coordinates))
return city_id
def write_activity(city_id,name,type):
sql = "INSERT INTO activity(city_id, type, name ) VALUES (%s,%s,%s) RETURNING id"
act_id = db_connector.write_into_db_with_return(sql,(city_id,type,name))
return act_id
def write_sentiment(act_id,data):
sql = "INSERT INTO sentiment(activity_id, stars, title, create_date, visit_date ) VALUES (%s,%s,%s,%s,%s)"
# print(data[1])
db_connector.write_into_db(sql, (act_id,data[0],data[1],data[3],data[2]))
# write_into_db( "INSERT INTO city(city_name, coordinates ) VALUES (%s,point%s) RETURNING id",('bsa',(1,2)))