我正在尝试在表中输入浮点数据。通过多次输入,我不会出错,但是表中没有任何输入。因此,尝试仅输入1列数据,我得到“浮动对象不可迭代。
这是在raspbian linux上。尝试了多件事。温度是来自Adafruit_DHT的浮动。 可以打印出值,但似乎无法将它们输入数据库。
#!/usr/bin/python
import sys
import Adafruit_DHT
import subprocess
import re
import os
import time
import MySQLdb as mdb
import datetime
databaseUsername="root"
databasePassword="jt"
databaseName="WordpressDB" #do not change unless you named the Wordpress database with some other name
sensor=Adafruit_DHT.DHT22 #if not using DHT22, replace with Adafruit_DHT.DHT11 or Adafruit_DHT.AM2302
pinNum=23 #if not using pin number 4, change here
def saveToDatabase(temperature, humidity):
con=mdb.connect("localhost", databaseUsername, databasePassword, databaseName)
currentDate=datetime.datetime.now().date()
now=datetime.datetime.now()
print (now)
cur=con.cursor()
#sql = "INSERT INTO temperatures (temperature, humidity, now) VALUES (%s, %s, %s)", (temperature, humidity, now)
#dataWritten = cur.execute("INSERT INTO Temperature (temperature, humidity, datetime) VALUES (%s, %s, %s)", (temperature, humidity, now))
dataWritten = cur.execute("INSERT INTO Temperature (temperature) VALUES (%s)", (temperature) )
print (dataWritten)
result = cur.fetchall()
cur.close()
return "true"
def readInfo():
humidity, temperature = Adafruit_DHT.read_retry(sensor, pinNum)#read_retry - retry getting temperatures for 15 times
temperature = temperature * 9.0 / 5.0 + 32.0
print(("Temperature: %.2f F" % temperature))
print(("Humidity: %.2f %%" % humidity))
if humidity is not None and temperature is not None:
return saveToDatabase(temperature,humidity) #success, save the readings
else:
print ('Failed to get reading. Try again!')
sys.exit(1)
status=readInfo() #get the readings
print (status)
I get float object is not iterable.
the table has only a auto increment int id and the temperature (6,3).
I am sure there is a simple fix, but it eludes me.
Error:
Temperature: 75.92 F
Humidity: 25.80 %
2019-05-19 16:01:33.198100
Traceback (most recent call last):
File "getInfo.py", line 54, in <module>
status=readInfo() #get the readings
File "getInfo.py", line 47, in readInfo
return saveToDatabase(temperature,humidity) #success, save the readings
File "getInfo.py", line 30, in saveToDatabase
dataWritten = cur.execute("INSERT INTO Temperature (temperature) VALUES (%s)", (temperature) )
File "/usr/local/lib/python3.5/dist-packages/MySQLdb/cursors.py", line 199, in execute
args = tuple(map(db.literal, args))
TypeError: 'float' object is not iterable