0
The.txt rain text file contains results of pH analysis of rainwater samples. Each of the lines has (separated by ";") the date of commencement of sampling (in the form YYYY-MM-DD), the duration of sampling (in hours), the identification of the location (a four-character sequence), the sampling point of the site (a number between 1 and 8) and the pH value measured.
I am trying to make a function that inserts the data from the file rain.txt in the table Samples from the database agua.db. The function should read the rain information.txt and for each line read insert this record in the Samples table.
def inserir_dadosBD(nomeBD,nomeFich,nomeTabela):
bd = sql.connect(nomeBD, isolation_level = None)
fich = open(nomeFich)
nomeTabela = 'CREATE TABLE ' + nomeTabela + '(Data TEXT, Hora INTEGER,
Local VARCHAR(4), Ponto INTEGER, pH REAL, PRIMARY KEY(Data));'
bd.execute(nomeTabela)
for linha in fich.readlines():
linha = linha.split(';')
Data = linha[0]
Hora = int(linha[1])
Local = linha[2]
Ponto = int(linha[3])
pH = float(linha[4])
com2 = 'INSERT INTO ' + nomeTabela + ' VALUES ('+ Data + ',' +
str(Hora) + ',' + Local + ',' + str(Ponto) + ',' + str(pH) + ');'
print(com2)
bd.execute(com2)
fich.close()
bd.close()
By calling inserir_dadosBD('agua.db','chuva.txt','Amostras')
and
bd = sql.connect('agua.db',isolation_level = None)
com = 'SELECT * FROM Amostras;'
res = bd.execute(com)
print(res.fetchall())
in the list of commands appears to me [('Data', 'Hora', 'Local', 'Ponto', 'pH')]
What do I have to change in the program to read what’s in the file rain.txt?
Thanks, I made a mistake: in my program the last 2 lines are inside the function. But why do I need to add bd.commit() ? I’ve never heard of this command in sqlite3. And I’ve already added bd.commit to the code after bd.execute(com2) and continues to appear only [('Data', 'Time', 'Local', 'Point', 'pH')]...
– stream
Since you are using the isolation_level=None parameter, you have configured the automatic commit.
– Hildeberto
Thank you but I didn’t understand why the "f" appears in this part with 2 = f"INSERT INTO {nameTable} VALUES ('{Data}' , {Time} , '{Place}' , {Point} , {pH});" ? And why did you print(com2) ? It’s not enough to make bd.execute(com2)?
– stream
It is new from version 3.6 of Python, called f-strings, for formatting strings.
– Hildeberto
but why did you use print(com2) and bd.execute(com2)?
– stream
I reproduced exactly what was in your code. I just fixed what was wrong... for the functionality the print is unnecessary.
– Hildeberto
OK thanks, also agree that should not be there the print (since it does not change anything)
– stream