如何将多部分字符串插入sqlite表

时间:2016-03-09 04:49:58

标签: python sqlite

我很难搞清楚如何从串口读取字符串,将其分解为部分并插入到sqlite表中。下面是我到目前为止的代码,但我错过了将字符串正确加载到sqlite中的正确语法。我无法更改传入的值。

#!/usr/bin/python
#--Arduino code calls this file when it detects flow during standard operation (i.e. when
#--not in calibration mode.  This code simply records the values from the sensor.
import serial
import sqlite3 as sqlite
#import sys

serial = serial.Serial("/dev/ttyUSB0", baudrate=115200)

code = ''

while True:
    data = serial.read()

    if data == '\r':
        (strdevice,strcount) = code.split(',',1)
        device = strdevice
        count = int(strcount)
        con = sqlite.connect('/mnt/sda1/sensor_flow_moteino.db')
        cur = con.cursor()
        cur.execute('''INSERT INTO data_log (device,count) VALUES(?,?)'''(device,count))
        con.commit()
        con.close()
        print(code)
        code = ''

    else:
        code = code + data

来自串口的传入数据的格式如下: “some_string,123”,其中第一个值是字符串,第二个值是整数。

0 个答案:

没有答案