使用SQLite和python3进行线程化

时间:2018-04-30 13:42:54

标签: python python-3.x sqlite tkinter

我正在尝试使用python3尽快将数据写入SQLite数据库,并且还运行tkinter GUI。 我有两个读取数据的传感器,我想将这些数据写入SQL。我收到了错误:

sqlite3.OperationalError: cannot start a transaction within a transaction

有人可以指出我正确的方向吗?在另一笔交易发生之前,是否需要花费一定的时间?

代码:

import threading
from tkinter import *
from tkinter.ttk import *
import tkinter as tk
from tkinter import ttk
import sqlite3
import time
from datetime import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from dateutil import parser
import random

conn = sqlite3.connect('testDB.db', check_same_thread=False)

class GUI(Frame): # test tkinter GUI

    def __init__(self, root):
        Frame.__init__(self, root)
        self.root = root
        self.button1 = Button(self.root, text="above", command = self.test_functionA)
        self.button1.pack()
        self.button2 = Button(self.root, text="below", command = self.test_functionB)
        self.button2.pack()

    def test_functionA(self):
        pass

    def test_functionB(self):
        pass


def simulated_sensor1(a,b):
    unix = int(time.time())
    date = str(datetime.fromtimestamp(unix).strftime('%Y-%m-%d %H:%M:%S'))
    x=1 #to keep while loop running
    cursor1 = conn.cursor()
    cursor1.execute("CREATE TABLE IF NOT EXISTS sensorA (unix REAL, 
    datestamp TEXT, value REAL)")

    while (x==1):
        simSensor1 = random.randint(a,b)
        cursor1.execute("INSERT INTO sensorA (unix, datestamp, value) VALUES (?, ?, ?)",(unix, date, simSensor1))
        time.sleep(1)
        conn.commit()
        print(simSensor1)

def simulated_sensor2(a,b):
    unix = int(time.time())
    date = str(datetime.fromtimestamp(unix).strftime('%Y-%m-%d %H:%M:%S'))
    x=1 #to keep while loop running
    cursor2 = conn.cursor()
    cursor2.execute("CREATE TABLE IF NOT EXISTS sensorB (unix REAL, datestamp TEXT, value REAL)")
    while (x==1):
        simSensor2 = random.randint(a,b)
        cursor2.execute("INSERT INTO sensorB (unix, datestamp, value) VALUES (?, ?, ?)",(unix, date, simSensor2))
        time.sleep(1)
        conn.commit()
        print(simSensor2)

def main():
    threadA = threading.Thread(target=simulated_sensor1, args=(1,10))
    threadA.start()
    threadB = threading.Thread(target=simulated_sensor2, args=(1,10))
    threadB.start()
    root = Tk()
    ex = GUI(root)
    root.mainloop()


if __name__ == '__main__':
        main()  

0 个答案:

没有答案