-
Notifications
You must be signed in to change notification settings - Fork 0
/
DB.py
229 lines (195 loc) · 6.02 KB
/
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
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import numpy as np
import pandas as pd
import psycopg2
import streamlit as st
from decouple import config
from sqlalchemy import exc
class DBoperations:
def __init__(self, host, database, user, password, port) -> None:
self.host = host
self.database = database
self.user = user
self.password = password
self.port = port
def DBConnect(self, dbName=None):
try:
# engine = create_engine(
# 'postgresql+psycopg2://postgres:password@localhost/twitter')
conn = psycopg2.connect(
database=self.database, user=self.user, password=self.password, host=self.host, port=self.port
)
cursor = conn.cursor()
cursor.execute("select version()")
data = cursor.fetchone()
print("Connection established to: ", data)
return conn, cursor
except exc.SQLAlchemyError as e:
print("Error", e)
# conn = mysql.connector.connect(host='localhost', port="3306", user='root', password="",
# database=dbName)
def createDB(self) -> None:
"""
Parameters
----------
dbName :
str:
dbName :
str:
dbName:str :
Returns
-------
"""
conn, cur = DBoperations.DBConnect(self)
# cur.execute(f"CREATE DATABASE IF NOT EXISTS {dbName};")
return conn
# conn.commit()
# cur.close()
def createTables(self, dbName: str) -> None:
"""
Parameters
----------
dbName :
str:
dbName :
str:
dbName:str :
Returns
-------
"""
conn, cur = DBoperations.DBConnect(self, 'tweets')
sqlFile = './schema.sql'
fd = open(sqlFile, 'r')
readSqlFile = fd.read()
fd.close()
sqlCommands = readSqlFile.split(';')
for command in sqlCommands:
try:
res = cur.execute(command)
except Exception as ex:
print("Command skipped: ", command)
print(ex)
conn.commit()
cur.close()
return
def preprocess_df(self, df: pd.DataFrame) -> pd.DataFrame:
"""
Parameters
----------
df :
pd.DataFrame:
df :
pd.DataFrame:
df:pd.DataFrame :
Returns
-------
"""
cols_2_drop = ['Unnamed: 0']
try:
df = df.drop(columns=cols_2_drop, axis=1)
df = df.fillna(0)
except KeyError as e:
print("Error:", e)
return df
def insert_to_tweet_table(self, dbName: str, df: pd.DataFrame, table_name: str) -> None:
"""
Parameters
----------
dbName :
str:
df :
pd.DataFrame:
table_name :
str:
dbName :
str:
df :
pd.DataFrame:
table_name :
str:
dbName:str :
df:pd.DataFrame :
table_name:str :
Returns
-------
"""
conn, cur = DBoperations.DBConnect(self, 'telco')
df = DBoperations.preprocess_df(self, df)
for _, row in df.iterrows():
# print(len(row))
# print(row)
# exit()
sqlQuery = f"""INSERT INTO {table_name} (created_at, msisdn, user_engagment, user_experience)
VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);"""
data = (row[1], row[2], row[3], (row[4]))
try:
# Execute the SQL command
cur.execute(sqlQuery, data)
# Commit changes in the database
conn.commit()
print("Data Inserted Successfully")
except Exception as e:
conn.rollback()
print("Error: ", e)
return
def db_execute_fetch(self, *args, many=False, tablename='', rdf=True, **kwargs) -> pd.DataFrame:
"""
Parameters
----------
*args :
many :
(Default value = False)
tablename :
(Default value = '')
rdf :
(Default value = True)
**kwargs :
Returns
-------
"""
connection, cursor1 = DBoperations.DBConnect(self, 'tweets')
if many:
cursor1.executemany(*args)
else:
cursor1.execute(*args)
# get column names
field_names = [i[0] for i in cursor1.description]
# get column values
res = cursor1.fetchall()
# get row count and show info
nrow = cursor1.rowcount
if tablename:
print(f"{nrow} records from {tablename} table")
cursor1.close()
connection.close()
# return result
if rdf:
return pd.DataFrame(res, columns=field_names)
else:
return res
st.set_page_config(page_title="Dashboard", layout="wide")
# def app():
# try:
# engine = create_engine(
# 'postgresql+psycopg2://postgres:password@localhost/twitter')
# except exc.SQLAlchemyError as e:
# print("Error", e)
# st.title('Data')
# st.write("This is the `Data` page of the multi-page app.")
# st.write("The following is the DataFrame of the `iris` dataset.")
# iris = datasets.load_iris()
# X = pd.DataFrame(iris.data, columns=iris.feature_names)
# Y = pd.Series(iris.target, name='class')
# df = pd.concat([X, Y], axis=1)
# df['class'] = df['class'].map(
# {0: "setosa", 1: "versicolor", 2: "virginica"})
# st.write(df)
if __name__ == '__main__':
host = config('Host', default='')
database = config('Database', default='')
user = config('User', default='')
password = config('Password', default='')
port = config('Port', default='')
db1 = DBoperations(host, database, user, password, port)
db1.createDB()
df = pd.read_csv('../clean_data_outliers.csv')
db1.insert_to_tweet_table('Teleco', df=df, table_name='telecoanalysis')