pessoal eu fiz o codigo idêntico ao que vocês disponibilizaram literalmente copiei e colei achando que foi algum erro meu então decidi copiar e colar o seus e mesmo assim diz que não está encontrando o local.
import os
from dotenv import load_dotenv
import mysql.connector
import pandas as pd
from mysql.connector import Error
# Carregar variáveis de ambiente
load_dotenv()
user = os.getenv("DB_USERNAME")
password = os.getenv("DB_PASSWORD")
host = os.getenv("DB_HOST")
import mysql.connector
import pandas as pd
def connect_mysql(host_name, user_name, pw):
cnx = mysql.connector.connect(
host = host_name,
user = user_name,
password = pw
)
print(cnx)
return cnx
def create_cursor(cnx):
cursor = cnx.cursor()
return cursor
def create_database(cursor, db_name):
cursor.execute(f"CREATE DATABASE {db_name}")
print(f"\nBase de dados {db_name} criada")
def show_databases(cursor):
cursor.execute("SHOW DATABASES")
for x in cursor:
print(x)
def create_product_table(cursor, db_name, tb_name):
cursor.execute(f"""
CREATE TABLE IF NOT EXISTS {db_name}.{tb_name}(
id VARCHAR(100),
Produto VARCHAR(100),
Categoria_Produto VARCHAR(100),
Preco FLOAT(10,2),
Frete FLOAT(10,2),
Data_Compra DATE,
Vendedor VARCHAR(100),
Local_Compra VARCHAR(100),
Avaliacao_Compra INT,
Tipo_Pagamento VARCHAR(100),
Qntd_Parcelas INT,
Latitude FLOAT(10,2),
Longitude FLOAT(10,2),
PRIMARY KEY (id));
""")
print(f"\nTabela {tb_name} criada")
def show_tables(cursor, db_name):
cursor.execute(f"USE {db_name}")
cursor.execute("SHOW TABLES")
for x in cursor:
print(x)
def read_csv(path):
df = pd.read_csv(path)
return df
def add_product_data(cnx, cursor, df, db_name, tb_name):
lista = [tuple(row) for _, row in df.iterrows()]
sql = f"INSERT INTO {db_name}.{tb_name} VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
cursor.executemany(sql, lista)
print(f"\n {cursor.rowcount} dados foram inseridos na tabela {tb_name}.")
cnx.commit()
if __name__ == "__main__":
# realizando a conexão com mysql
cnx = connect_mysql(host, user, password)
cursor = create_cursor(cnx)
# criando a base de dados
create_database(cursor, "db_produtos_teste")
show_databases(cursor)
# criando tabela
create_product_table(cursor, "db_produtos_teste", "tb_livros")
show_tables(cursor, "db_produtos_teste")
#lendo e adicionando os dados
df = read_csv("../data/tb_livros.csv")
add_product_data(cnx, cursor, df, "db_produtos_teste", "tb_livros")
ele retorna:
<mysql.connector.connection_cext.CMySQLConnection object at 0x7f1fd5add570> Traceback (most recent call last): File "/home/duda/pipeline-python-mongo-mysql/scripts/save_data_mysql.py", line 94, in df = pd.read_csv("../data/tb_livros.csv") File "/home/duda/pipeline-python-mongo-mysql/venv/lib/python3.10/site-packages/pandas/util/_decorators.py", line 211, in wrapper return func(*args, **kwargs) File "/home/duda/pipeline-python-mongo-mysql/venv/lib/python3.10/site-packages/pandas/util/_decorators.py", line 331, in wrapper return func(*args, **kwargs) File "/home/duda/pipeline-python-mongo-mysql/venv/lib/python3.10/site-packages/pandas/io/parsers/readers.py", line 950, in read_csv return _read(filepath_or_buffer, kwds) File "/home/duda/pipeline-python-mongo-mysql/venv/lib/python3.10/site-packages/pandas/io/parsers/readers.py", line 605, in _read parser = TextFileReader(filepath_or_buffer, **kwds) File "/home/duda/pipeline-python-mongo-mysql/venv/lib/python3.10/site-packages/pandas/io/parsers/readers.py", line 1442, in init self._engine = self._make_engine(f, self.engine) File "/home/duda/pipeline-python-mongo-mysql/venv/lib/python3.10/site-packages/pandas/io/parsers/readers.py", line 1735, in _make_engine self.handles = get_handle( File "/home/duda/pipeline-python-mongo-mysql/venv/lib/python3.10/site-packages/pandas/io/common.py", line 856, in get_handle handle = open( FileNotFoundError: [Errno 2] No such file or directory: '../data/tb_livros.csv'