如何在python中将返回值插入mysql数据库?

时间:2014-11-20 23:15:22

标签: 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 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()

1 个答案:

答案 0 :(得分:0)

假设'warnings'是唯一的错误 - 那么只需要从python类型转换为SQL数据库的列类型。有可能,你的python类型设置的精度高于表中的列。这就是'截断'的含义。数据正在被砍掉。您的表的列类型是什么?

如果您打算做很多数据库工作,我会推荐SQL Alchemy或其他对象关系映射器,它可以帮助您避免像这样的小的不一致。