如何在不每次打开sqlite连接的情况下运行功能

时间:2020-01-26 18:58:39

标签: python sql database sqlite

我在下面有此代码。每次函数运行时,都不会将数据添加到数据库中,因为我没有连接到函数内部的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')

1 个答案:

答案 0 :(得分:0)

我只是将下面的代码添加到“ on message”功能中。我猜想我必须连接到函数中的数据库,以前我以为如果我在脚本之外建立连接,那么函数将实现连接。

conn = sqlite3.connect('hist_data.db')
c = conn.cursor()