如何使用python 2.7将变量值插入mysql?

时间:2016-04-03 11:58:12

标签: python mysql datetime

我想使用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而不是它们的值:

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

2 个答案:

答案 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方法

中的