python+数据库+传感器(简易版)

版权声明:转载请标明链接, https://blog.csdn.net/qq_43433255/article/details/86985964

这是一个简单的说明,推荐链接:https://blog.csdn.net/qq_43433255/article/details/86767399

这一个模块,主要是,数据库与传感器的两个方面;

获得传感器数据的代码:

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
u'''
Created on
2019年1月7日

 
@author: wuluo
'''
__author__ = 'wuluo'
_version__ = '1.0.0'
__company__ = u'重庆交大'
__updated__ = '2019-01-09'

import socket
import codecs
import time

# 创建套接字,绑定套接字到本地IP与端口

sk =socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sk.connect(('10.1.156.82', 8001))
inp = '030300000002c5e9'
while True:
    if inp == 'exit':
        print("exit")
        break  # 默认编码为十六进制编码
    sk.send(codecs.decode(inp, 'hex'))
    # 每次接受1024字节的数据
    result = sk.recv(1024)
    result = codecs.encode(result, 'hex')
    r = bytes(result).decode('utf-8')
    shidu = int(r[6:10], 16) / 100
    wendu = int(r[10:14], 16) / 100
    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    print("温度:%s,湿度:%s\n" % (wendu, shidu))
    # 每2秒读取以此数据
    time.sleep(3)
sk.close()

数据库的代码:

#!/usr/bin/env python3
# -*- coding:utf-8 -*
u'''
Created on
2019年1月7日

@author: wuluo

'''
__author__ = 'wuluo'
__version__ = '1.0.0'
__company__ = u'重庆交大'
__updated__ = '2019-01-09'

import pymysql

'''=0=连接数据库,绑定数据库python_wensidu.db'''
con = pymysql.connect(
    host='127.0.0.1',
    port=3306,
    user='root',
    password='密码',
    db='python_wensidu',
    charset='utf8'
)
cur = con.cursor()  # 定义一个游标,通过游标来操作数据库
'''=1=查询数据库存中的所有表格'''
row = cur.execute('show tables')
# print(row)
'''=2=读取所有表数据'''
all = cur.fetchall()


'''
cur.executemany("INSERT
wensidu VALUE(%s,%s,%s)", [
              ('test2', '7', '49'), ('test3',
'9', '81')])# 插入多条数据到数据库
con.commit()'''
'''=5=读取数据库'''
select = cur.execute('SELECT * FROM wensidu')
all = cur.fetchall()
print(all)

代码仅供参考!

猜你喜欢

转载自blog.csdn.net/qq_43433255/article/details/86985964