首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么我在python中不能使用mysql Insert命令?

为什么我在python中不能使用mysql Insert命令?
EN

Stack Overflow用户
提问于 2019-02-28 04:38:14
回答 1查看 85关注 0票数 0

查询是正确的,但我不明白为什么它不能添加到我的数据库中。请帮帮我谢谢。我是一个初学者,我几乎不能调试这个。

代码语言:javascript
复制
    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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-28 11:43:19

你可以试试..。

代码语言:javascript
复制
sql = "INSERT INTO res(celsius,fahrenheit,humidity,flame) VALUES(%s,%s,%s,%s)"
data = (cel, far, hum, fla)

指定所需的值并使其更清晰,也会遗漏db.commit()

这样,您就执行了命令,并将它的值传递给sql

然后你就可以提交你的数据库了。

db.commit()

然后关闭连接。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54914096

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档