1.根据网络配置mosquitto
略
2.测试通讯是否成功
mosquitto_pub # 消息发布
mosquitto_sub # 消息订阅
3.实现将监听的数据存入数据库
1.将数据重定向到csv或者txt文件中
mosquitto_sub *** >> test.csv
2.将文本文件遍历逐行存入数据库
import json
import pymysql
import os
import time
def readfile(row):
with open('test.csv','r') as file:
rowed = row #记录上次读取的行数
for n,i in enumerate(file):
print(n)
if n<rowed:
continue
print(i.strip('\n'))
data = eval(i.strip('\n'))
id =data[0]
cursor.execute('select id from testdata_test')
ids = cursor.fetchall()
ids = [x['id'] for x in ids]
if id in ids:
print("zai")
cursor.execute('update testdata_test set no={},name="what",age={} where id={}'.format(data[1],data[3],data[0]))
print("更新完成!")
else:
cursor.execute('INSERT INTO testdata_test values({},{},"{}",{})'.format(data[0],data[1],data[2],data[3]))
print("添加完成!")
row = n
time.sleep(5)
readfile(row)
config = {
'host': '127.0.0.1',
'port': 3306,
'user': 'root',
'passwd': '123456',
'db':'testdata',
'cursorclass':pymysql.cursors.DictCursor
}
conn = pymysql.connect(**config)
conn.autocommit(1)
cursor = conn.cursor()
#关闭游标