-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_connection.py
109 lines (95 loc) · 3.29 KB
/
db_connection.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
import mysql.connector
from mysql.connector import Error
import configparser
import pandas as pd
from tabulate import tabulate
def read_db_config(filename='db_config.ini', section='mysql'):
parser = configparser.ConfigParser()
parser.read(filename)
db_config = {}
if parser.has_section(section):
items = parser.items(section)
for item in items:
db_config[item[0]] = item[1]
else:
raise Exception(f'Section {section} not found in the {filename} file')
return db_config
def connect_database():
try:
config = read_db_config()
connection = mysql.connector.connect(**config)
if connection.is_connected():
return connection
else:
return -1
except Error as e:
print("Erro ao conectar ao MySQL", e)
def create_table_coins(connection, cursor, df_coins):
create_table_query = """
CREATE TABLE IF NOT EXISTS coins_prices (
id INT,
market_cap DECIMAL(38, 2),
price DECIMAL(20, 8),
last_updated DATETIME
)
"""
try:
cursor.execute(create_table_query)
for index, row in df_coins.iterrows():
insert_query = """
INSERT INTO coins_prices (id, market_cap, price, last_updated) VALUES (%s, %s, %s, %s)
"""
cursor.execute(insert_query, tuple(row))
connection.commit()
except Error as e:
print("Erro ao criar a tabela de coins", e)
def check_table_exists(connection, cursor, table_name):
cursor.execute(f"SHOW TABLES LIKE '{table_name}';")
result = cursor.fetchone()
if result:
return True
else:
return False
def create_table_names(connection, cursor, df_names):
create_table_query = """
CREATE TABLE IF NOT EXISTS coins_names (
id INT NOT NULL,
name VARCHAR(255) NOT NULL,
symbol VARCHAR(10) NOT NULL,
logo VARCHAR(255),
category VARCHAR(50),
description TEXT,
website VARCHAR(255),
PRIMARY KEY (id)
)
"""
try:
cursor.execute(create_table_query)
for index, row in df_names.iterrows():
insert_query = """
INSERT INTO coins_names (id, name, symbol, logo, category, description, website) VALUES (%s, %s, %s, %s, %s, %s, %s)
"""
cursor.execute(insert_query, tuple(row))
connection.commit()
except Error as e:
print("Erro ao criar a tabela de names", e)
def get_ids_names(connection, cursor):
#essa função retorna os ids das moedas que já existem na tabela coins_names
cursor.execute("SELECT id FROM coins_names")
records = cursor.fetchall()
return records
def print_names(cursor):
#não imprimi todas as informações pq fica dificil de visualizar
query = "SELECT id, name, symbol, category FROM coins_names"
cursor.execute(query)
results = cursor.fetchall()
columns = cursor.column_names
df = pd.DataFrame(results, columns=columns)
print(tabulate(df, headers='keys', tablefmt='psql'))
def print_values(cursor):
query = "SELECT * FROM coins_prices"
cursor.execute(query)
results = cursor.fetchall()
columns = cursor.column_names
df = pd.DataFrame(results, columns=columns)
print(tabulate(df, headers='keys', tablefmt='psql'))