如何在python中向mysql数据库插入返回值?
我试着为我的pi做一个项目。我想读取温度并将温度值插入数据库。我可以读取温度,但无法将其插入数据库。谁能告诉我哪里出了错?谢谢你的帮助。致以最良好的祝愿:如何在python中向mysql数据库插入返回值?,python,mysql,Python,Mysql,我试着为我的pi做一个项目。我想读取温度并将温度值插入数据库。我可以读取温度,但无法将其插入数据库。谁能告诉我哪里出了错?谢谢你的帮助。致以最良好的祝愿: #!/usr/bin/python # -*- coding: utf-8 -*- import requests import hashlib import time import MySQLdb #Dont forget to fill in PASSWORD and URL TO saveTemp (twice) in this fil
#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
import hashlib
import time
import MySQLdb
#Dont forget to fill in PASSWORD and URL TO saveTemp (twice) in this file
sensorids = ["28-00042d99c9ff", "28-00042d99c9ff"]
avgtemperatures = []
for sensor in range(len(sensorids)):
temperatures = []
for polltime in range(0,3):
text = '';
while text.split("\n")[0].find("YES") == -1:
# Open the file that we viewed earlier so that python can see what is in it. Replace the serial number as before.
tfile = open("/sys/bus/w1/devices/"+ sensorids[sensor] +"/w1_slave")
# Read all of the text in the file.
text = tfile.read()
# Close the file now that the text has been read.
tfile.close()
time.sleep(1)
# Split the text with new lines (\n) and select the second line.
secondline = text.split("\n")[1]
# Split the line into words, referring to the spaces, and select the 10th word (counting from 0).
temperaturedata = secondline.split(" ")[9]
# The first two characters are "t=", so get rid of those and convert the temperature from a string to a number.
temperature = float(temperaturedata[2:])
# Put the decimal point in the right place and display it.
temperatures.append(temperature / 1000 )
avgtemperatures.append(sum(temperatures) / float(len(temperatures)))
print avgtemperatures[0]
print avgtemperatures[1]
# Open database connection
db = MySQLdb.connect("my db-ip", "my user name", "my pass", "my db name" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = "INSERT INTO temps(temp1,temp2) VALUES (avgtemperatures[0], avgtemperatures[1])"
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
假设“警告”是唯一的错误,那么只需要将python类型转换为SQL数据库的列类型。很可能,python类型的设置精度高于表中的列。这就是“截断”的意思。数据正在被切断。表的列类型是什么
如果你打算做大量的数据库工作,我建议你使用SQL Alchemy或其他对象关系映射器,它们可以帮助你避免像这样的小不一致 运行此操作时会出现什么错误?这是错误消息,我的朋友。Temple.py:50:警告:第1行光标处的列“temp1”的数据被截断。executesql Temple.py:50:警告:第1行光标处的列“temp2”的数据被截断。executesql感谢您的快速回答,我的朋友。我的表数据类型是temp1 float、temp2 float、id int。我无法解决这个问题:我无法理解为什么我的代码没有运行。看起来是正确的。也许您应该尝试将列设置为十进制而不是浮点。