如何使用python检索数据MySQL值

时间:2016-04-04 14:07:18

标签: python mysql sockets python-3.x udp

我尝试从UDP套接字接收值并将其发送到MySQL数据库并将其放入传感器表中。然后我尝试从MySQL数据库中的动作表中检索数据并通过UDP套接字发回。我使用python 3.5。

这是我的Python代码。

from random import *
import sys
import pymysql
#from datetime import datetime
from socket import *
import time

UDP_IP="192.168.1.26"
UDP_PORT = 6009
UDP_PORT2 = 5016

address= ('192.168.1.207' , 5454)
client_socket = socket(AF_INET , SOCK_DGRAM)
client_socket.settimeout(1)
sock = socket (AF_INET , SOCK_DGRAM)
sock.bind((UDP_IP , UDP_PORT))
sock2 = socket(AF_INET , SOCK_DGRAM)
sock2.bind((UDP_IP , UDP_PORT2))

conn = pymysql.connect(host='127.0.0.1', user='root', passwd='', db='iot',port=3306)
x = conn.cursor()
try:
         x.execute("""INSERT INTO sensors VALUES (%s,%s)""",(0,0))
         conn.commit()
except:
        conn.rollback()

while True :

    data1 = "Temperature"

    client_socket.sendto(data1.encode("UTF-8") , address)

    rec_data1,addr = sock.recvfrom(2048)

    temperature = float(rec_data1)

    print (temperature)

    data2 = "humidity"

    client_socket.sendto(data2.encode("UTF-8") , address)

    rec_data2 , addr =sock2.recvfrom(2048)

    humidity = float(rec_data2)

    print (humidity)

    x.execute("""TRUNCATE TABLE `sensors`;""")
    x.execute("""INSERT INTO sensors VALUES (%s,%s)""",(temperature,humidity))
    conn.commit()
    time.sleep(1)

    x.execute("""Select tempout from action; """)
    data3 = x.fetchall()
    print(data3)
    x.execute("""Select humout from action;""")
    data4 = x.fetchall()
    print (data4)

    client_socket.sendto(data3.encode("UTF-8"), address)
    client_socket.sendto(data4.encode("UTF-8") , address)

这是我得到的错误:

  

25.12   240.0((' ON_1',),)((' OFF_2',),)回溯(最近一次呼叫最后一次):文件" C:\ Users \ ghina \ Desktop \ Mysql + socketUDP.py",第62行,在       client_socket.sendto(data3.encode(),address)AttributeError:' tuple'对象没有属性'编码'

0 个答案:

没有答案