简体   繁体   English

为什么mysql Insert命令在python中对我不起作用?

[英]Why is the mysql Insert command not working for me in python?

The query is correct but I do not understand why it cannot be added into my database. 该查询是正确的,但我不明白为什么无法将其添加到我的数据库中。 Please help me thanks. 请帮我谢谢。 I am a beginner and I can hardly debug this one. 我是一个初学者,几乎无法调试它。

    def callback(channel):
    print("\nflame detected\n")

GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300)#pin if HIGH or LOW
GPIO.add_event_callback(channel, callback)       


while True:

    db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="results")
    #create a cursor for the select
    cur = db.cursor()
    result = instance.read()
    if result.is_valid():
        print("Last valid input: " + str(datetime.datetime.now()))
        print("Temperature: %d C" % result.temperature)
        print("Temperature: %d F" % ((result.temperature*9/5)+32))
        print("Humidity: %d %%" % result.humidity)

        cel = str(result.temperature)
        far = str((result.temperature*9/5)+32)
        hum = str(result.humidity)
        fla = "No Flame"




    #execute an sql query
    sql = "INSERT INTO res(celsius,fahrenheit,humidity,flame) VALUES('"+cel+"','"+far+"','"+hum+"','"+fla+"')"
    cur.execute(sql)

        # close the cursor
    cur.close()

    # close the connection
    db.close ()
    time.sleep(1)

You can try ... 你可以试试 ...

sql = "INSERT INTO res(celsius,fahrenheit,humidity,flame) VALUES(%s,%s,%s,%s)"
data = (cel, far, hum, fla)

Specifying the need values and making it clearer, also you're missing the db.commit() 指定需求值并使其更清晰,您也会缺少db.commit()

cur.execute(sql, data) with this you have executed the command also passing it's value to sql cur.execute(sql, data)与此一起执行了命令,并将其值传递给sql

then after that you can commit your db. 然后,您可以提交您的数据库。

db.commit()

then close the connection. 然后关闭连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM