Python 如何将多部分字符串插入sqlite表
我一直在琢磨如何从串口读取字符串,将其分解成各个部分并插入到sqlite表中。下面是我到目前为止的代码,但是我缺少将字符串正确加载到sqlite中的正确语法。我无法更改传入值Python 如何将多部分字符串插入sqlite表,python,sqlite,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
#!/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”,其中第一个值是一个字符串,第二个值是一个整数。听起来你想
拆分逗号上的代码字符串:(somestring,number)=code.split(',',,1)
然后对这两部分进行任何额外的处理。(例如,您可能想使用int(number)
,因为拆分后它将是一个字符串。)@AustinHastings感谢您的建议。我在代码中添加了您的注释,但在cur.execute行上得到了{TypeError:'str'object not callable}。您需要在三引号字符串的末尾加一个逗号:'(device