我想使用mysql数据库(db name:project)将变量(temp,hum)的值插入到我的表传感器中。我正在使用Ubuntu 14.04,并且在python和MySQL之间建立连接,但是我不能把变量的值。所以欢迎任何帮助,谢谢。
这是我的脚本Python:
from random import *
import socket
import sys
import mysql.connector
from datetime import datetime
temp = randrange(10, 31, 2)
hum = randrange(300, 701, 2)
print temp
print hum
conn=mysql.connector.connect(user='root',password='12345',host='localhost',database='projet');
mycursor=conn.cursor();
mycursor.execute("""INSERT INTO sensors VALUES('$datetime','$temp','$hum')""");
conn.commit()
mycursor.execute("SELECT * FROM sensors")
这是我的表格,您可以在其中找到变量temp和hum而不是它们的值:
答案 0 :(得分:1)
那是因为您没有将变量值传递给查询。将查询传递给execute()
方法:
mycursor.execute("""
INSERT INTO
sensors
VALUES
('$datetime', %s, %s)""", (temp, hum))
其中%s
是查询参数的占位符。请注意,数据库驱动程序将处理参数类型转换并自动转义。
至于$datetime
,如果您希望在此列中包含当前日期/日期时间,请查看使用NOW()
或CURDATE()
,请参阅:
答案 1 :(得分:0)
但我不能把变量的值
假设data-time是一个字符串,其余是整数
尝试
"INSERT INTO sensors VALUES('%s','%d','%d')", %(date, temp, num)
execute
方法中的