2016-04-03 76 views
1

我想使用mysql数据库(db名称:project)将变量(temp,hum)的值插入到我的表格传感器中。我使用的是Ubuntu 14.04,并且在python和MySQL之间建立了连接,但是我无法放置变量的值。所以任何帮助都是值得欢迎的,谢谢。如何使用python 2.7将变量的值插入到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和嗡嗡声,而不是它们的值:

This is my table where you can find the variables temp and hum and not their values

+0

** WARNING **:请小心[正确逃生(HTTP://鲍比桌。 com/python.html)这些值。直接插入数据非常危险。 – tadman

回答

1

那是因为你不及格将查询中的变量值。与查询到​​方法将它们传递:

mycursor.execute(""" 
    INSERT INTO 
     sensors 
    VALUES 
     ('$datetime', %s, %s)""", (temp, hum)) 

其中%s是查询参数占位符。请注意,数据库驱动程序将自动处理参数类型转换和转义。

至于$datetime,如果你想在此列当前日期/日期时间,考虑使用NOW()CURDATE(),请参阅:

0

,但我可以放置变量的值

假设数据时间是一个字符串,其余均为整数

尝试

"INSERT INTO sensors VALUES('%s','%d','%d')", %(date, temp, num) 

execute方法

+0

您确定该语法有效吗? – alecxe