python - 为什么 mysql Insert 命令在 python 中对我不起作用?
问题描述
查询是正确的,但我不明白为什么它不能添加到我的数据库中。请帮帮我谢谢。我是初学者,我几乎无法调试这个。
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)
解决方案
你可以试试 ...
sql = "INSERT INTO res(celsius,fahrenheit,humidity,flame) VALUES(%s,%s,%s,%s)"
data = (cel, far, hum, fla)
指定需要值并使其更清晰,您也错过了db.commit()
cur.execute(sql, data)
有了这个,你已经执行了命令,还将它的值传递给sql
然后你可以提交你的数据库。
db.commit()
然后关闭连接。
推荐阅读
- bootstrap-4 - 手动安装 Bootstrap4
- oracle - 如何计算 ORACLE 中 2 列之和的平均值?
- python - 从嵌套为python中字典值的两个列表中检索数据的最有效方法
- python - Bokeh 可以检测屏幕尺寸并重塑移动设备的布局吗?
- c++ - 交换两个对象的两个属性的值
- python - txt 与 dict 的 str 成 dict
- amazon-cloudwatch - CloudWatch Log Insights 中的多方面时间序列可视化
- compiler-construction - 转译/代码生成 - 变量声明问题
- javafx - 尝试使用 FXML 文件进行编译时,JavaFX 程序不起作用
- python - 错误:[Index(['...'], dtype='object')] 中没有一个在 [index] 中