1
Hi, I’m writing an algorithm that collects information from dividend companies. The collection is performed and mounts a table and up to this point everything excellent. but I would like to save in a database and am using Python Sqlite 3. The table is perfect, the problem is when I try to insert in the bank. I believe the error is in the "FOR" loop, but I still can’t unravel.
connection = sqlite3.connect('dividendos.db')
con = connection.cursor()
def create_table():
con.execute('CREATE TABLE IF NOT EXISTS dados (Empresa text, Tipo text, Data_Ex text, Data_Pag text, Valor text)')
create_table()
def data_entry():
for empresa in tabela['Empresa']:
empresa = str(empresa)
for tipo in tabela['Tipo']:
tipo = str(tipo)
con.execute("INSERT INTO dados VALUES('"+empresa+"','"+tipo+"','DataEx','DataPag','Valor')")
connection.commit()
data_entry()
No errors returned, just not saving as it should. I can do only one "FOR" to read the whole table, go assigning and only then enter the values in the database?
In the column company will receive from the table table[2ª Company']. So that way you put it works ?
– Edu Barros
I didn’t quite understand the question... I added at the end of the answer an example data frame. That’s how it will be inserted and returned. If your data frame is different, the code
tabela.to_sql
works because it saves the data frame.– lmonferrari
I assign the values of the variables and they look like this: company = table['Company'] type = table['Type'] dataex = table['Dataex'] datapag = table['Prevpag'] value = table['Value'] but in the end gave this error: Valueerror: could not broadcast input array from Shape (2) into Shape (19)
– Edu Barros
The way I posted the answer, you already created the fields in the database, right? What pd.to_sql does is associate the column names with the table columns. So it records without you having to do these assignments in separate variables. Did you test the code I posted? If you have any questions post your dataset I try to help you. Hug!
– lmonferrari
It worked, it was perfect! And much simpler. Now just one more thing, is it possible to write ? Instead of adding lines, stay only the new ? Or rather, save only if the line is not repeated.
– Edu Barros
Documentation, you can check to_sql methods and options. In this case ai can use instead of
append
thereplace
where is theif_exists
. If the answer has solved your problem, consider marking asaceita
. Big Hug!– lmonferrari