У меня есть этот код ниже. Каждый раз, когда функция запускается, она не добавляет данные в базу данных, потому что я не подключался к базе данных sqlite внутри функции. Как я могу запустить эту функцию без необходимости подключаться и отключаться от базы данных при каждом запуске функции. Это вообще возможно?
conn = sqlite3.connect('hist_data.db')
c = conn.cursor()
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
client.subscribe("MY TOPIC 1")
client.subscribe('MY TOPIC 2')
def on_message(client, userdata, msg):
print("this is the msg payload: " + str(msg.payload))
if str(msg.topic) == "MY TOPIC 1":
print('starts loop')
msg = msg.payload
msg = msg.decode('utf-8')
print("decoded message: " + msg)
msg = str(msg)
print("message as string: "+ msg)
msg = msg.rstrip()
print('msg stripped: '+msg)
print(type(msg))
msg = msg.split(" ")
ph = float(msg[0])
print(f'ph: {ph}')
water_level = int(msg[1])
print(f'water_level: {water_level}')
humidity = float(msg[2])
print(f'humidity: {humidity}')
air_temp = float(msg[3])
print(f"air_temp: {air_temp}")
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"timestamp: {timestamp}")
data = [(ph,air_temp,humidity,water_level,timestamp)]
print(f'this is the data in list tuple: {data}')
c.executemany("INSERT INTO sensor_data(ph,air_temp,humidity,water_level,timestamp) VALUES(?,?,?,?,?)",data)
print("it was executed")
conn.commit()
if str(msg.topic) == "MY TOPIC 2":
msg = msg.payload
water_temp = msg.decode('utf-8')
print(f'decoded msg : {water_temp}')
water_temp = float(water_temp)
c.execute("SELECT * FROM sensor_data WHERE timestamp = (SELECT MAX(timestamp) FROM sensor_data)")
print('inserted data')
c.execute("UPDATE sensor_data SET water_temp = (?) WHERE timestamp = (SELECT MAX(timestamp) FROM sensor_data)",(water_temp,))
print('updated it')
# c.execute("insert into sensor_data(water_temp) values(?)",[(ph),])
conn.commit()
print('done')