我敢肯定我犯了一个简单的错误,但是如果我能弄清楚的话,我会很惊讶。我正在使用RPi和DHT22制作温度/湿度监视器。代码在python中。效果很好。我想将收集的变量数据转储到MySQL数据库中,但是我的插入查询一直失败。我可以插入直字符串,但似乎无法弄清楚如何引用变量。这是我的代码

import time
time.sleep(2)
import MySQLdb
temperature = 60.0
humidity = 30.0
IP_Add = "123.456.78.9"
location = "basement"
name = "home"

while True:
    humidity = humidity
    temperature = temperature
    fTemperature = (temperature * 9 / 5) + 32
    name = 'home'
    if humidity is not None and temperature is not None:
        print('Temp={1:0.1f}  Humidity={0:0.1f}%'.format(temperature, humidity))
    else:
        print('Whoops')
    myDB = MySQLdb.connect(host="localhost", port = 3306, user = "root", passwd = "********", db = "PLAYTHING")
    cur = myDB.cursor()
    try:
        #query1 = "INSERT INTO `testdata`(`Name`) VALUES (name)"
        #query2 = "INSERT INTO `testdata`(`Name`, `Location`) VALUES (name, location)"
        #query3 = "INSERT INTO `testdata`(`Name`, `Location`, `T-Reading`)VALUES (%s, %s, %s)", ('No_ID2', 'basement',  30.5)
        query4 = "INSERT INTO `testdata`(`Name`, `Location`, `T-Reading`)VALUES {0} {1} {2}".format ('No_ID2', 'basement',  30.5)
        #query5 = "INSERT INTO testdata(`Name`, `Location`, `T-Reading`, `H-Reading`) VALUES ('Friday3', 'location', 72.5, 29.6)"


    cur.execute(query)
    myDB.commit()
    print ("Commit Sucessful")
except (MySQLdb.Error, MySQLdb.Warning) as e:
    print(e)
cur.close()
myDB.close()

time.sleep(10)


我已经在https://mysqlclient.readthedocs.io/user_guide.html#functions-and-attributes检查了MySQLdb文档
这提供了指导

"""INSERT INTO breakfast (name, spam, eggs, sausage, price)
  VALUES (%s, %s, %s, %s, %s)""",
  [
  ("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95 ),
  ("Not So Much Spam Plate", 3, 2, 0, 3.95 ),
  ("Don't Wany ANY SPAM! Plate", 0, 4, 3, 5.95 )
  ] )


但这似乎对我不起作用。

查询1和2执行但不输入数据,col的3和4为NULL。
查询3给我以下消息:“ TypeError:query()参数1必须是字符串或只读缓冲区,而不是元组”
查询4不输入任何数据,并提供以下信息:(1064,“您的SQL语法有错误;请查看与您的MariaDB服务器版本相对应的手册,以找到在第1行的'No_ID2地下室30.5'附近使用的正确语法”)
查询5成功,但是不能解决从程序获取变量并将其插入db的问题。

如果有人指出我的错误,我将不胜感激。

最佳答案

查询问题:

#1和#2:VALUES中的名称和位置(名称,位置)被视为数据库中的列名称,因此没有数据。

#3:正如Ilja所指出的,该元组应该在execute()调用中。这应该是要走的路。

        query3 = ("INSERT INTO `testdata`(`Name`, `Location`, `T-Reading`)"
                 + " VALUES (%s, %s, %s)")
        cur.execute(query3, ('No_ID2', 'basement',  30.5))


#4:要将值直接放入VALUES中,必须在字符串中加上引号。下面是正确的格式。注意:这仅用于实验,因为它会带来SQL注入安全风险。

        query4 = ("INSERT INTO `testdata`(`Name`, `Location`, `T-Reading`)"
                 + " VALUES ('{0}', '{1}', {2})".format (
                     'No_ID2', 'basement',  30.5
                 ))


#5:SQL语句中的所有值都是常量。

10-04 10:45
查看更多