-1
Hello. I’m learning sql now, I’m trying to make a simple python code to store 4 data in sql database. But every time I stop the code and run it again, it erases the bank and starts again. I couldn’t find anything on the Internet to help me, I need your help. I’ll leave my 3 codes here for you to see.
Just to illustrate, I get data from the Arduin card, and write it into the database.
My intention is to make an "analysis" of them in the future.
Just to remind I’m learning python and sqlite now, on account of college.
ambientData.py:
from os import error
import sqlite3
from sqlite3.dbapi2 import Error
from conexao import Conexao
class Ambient:
def cadastrar(self, umidade, temperatura, data, hora):
try:
conn = Conexao()
conexao = conn.conectar()
cursor = conexao.cursor()
sql = 'INSERT INTO Ambient (umidade, temperatura, data, hora) VALUES (?, ?, ?, ?)'
cursor.execute(sql, [umidade, temperatura, data, hora])
conexao.commit()
cursor.close()
conexao.close()
return True
except sqlite3.OperationalError as e:
print("Erro no cadastro de dados: {}".format(e))
return False
except sqlite3.IntegrityError as e:
print("Erro de integridade: {}".format(e))
return False
py connection.:
import sqlite3
class Conexao:
def conectar(self):
conexao = None
db_path = 'ambientData.db'
try:
conexao = sqlite3.connect(
db_path, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
except sqlite3.DatabaseError as err:
print(f"Erro ao conectar o banco de dados {db_path}.")
return conexao
def createTable(self, conexao, cursor):
cursor.execute('DROP TABLE IF EXISTS Ambient')
sql = """CREATE TABLE IF NOT EXISTS Ambient (
umidade varchar NOT NULL,
temperatura varchar NOT NULL,
data varchar NOT NULL,
hora carchar NOT NULL);"""
cursor.execute(sql)
conexao.commit()
def createTables(self):
conexao = self.conectar()
cursor = conexao.cursor()
self.createTable(conexao, cursor)
# Cria o banco e as tabelas
# Conexao().createTables()
main py.:
import serial
from datetime import datetime
from ambientData import Ambient
Arduino = serial.Serial('/dev/cu.usbmodem14701', 9600)
h = 0
t = 0
while True:
# receber os dados do arduino
arduino = str(Arduino.readline())
# tratar os dados recebidos
umidade = arduino[2:7]
temperatura = arduino[8:13]
# pegar hora e data do sistema
date = datetime.now().strftime('%d-%m-%Y %H:%M:%S')
data = date[0:10]
hora = date[11:19]
if (h != umidade or t != temperatura):
# somente a título de testagem
CRUD = Ambient()
CRUD.cadastrar(umidade, temperatura, data, hora)
h = umidade
t = temperatura
print('A data de hoje é: {}, a hora agora é: {}, a umidade do ambiente é: {}% e a temperatura ambiente é: {}°'.format(data, hora, umidade, temperatura))
arduino.close()
hi, in the method
createTable
you are deleted the table and creating again every time you run the code just remove thecursor.execute('DROP TABLE IF EXISTS Ambient')
, do not need to delete the table because it will only create the table if it does not exist.CREATE TABLE IF NOT EXISTS Ambient
– josué