1

I want to insert the value of variable (temp, hum) into my table sensors using mysql database (db name:project). I am using Ubuntu 14.04, and the connection is made between python and MySQL, but I can't put the value of the variable. So any help is welcome, and thanks.

This is my script 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")

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

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

alfakini
  • 4,635
  • 2
  • 26
  • 35
Allouch
  • 11
  • 1
  • 4
  • **WARNING**: Please be careful to [properly escape](http://bobby-tables.com/python.html) those values. Inserting data directly is really dangerous. – tadman Apr 03 '16 at 12:01

2 Answers2

1

That's because you are not passing the variable values into the query. Pass them with the query into the execute() method:

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

where %s are placeholders for the query parameters. Note that the database driver would handle the parameter type conversion and escaping automatically.

As for the $datetime, if you want to have a current date/datetime in this column, look into using NOW() or CURDATE(), see:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
0

but i can't put the value of variable

Assuming data-time is a string and the rest are integers

Try

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

in the execute method

vozille
  • 115
  • 1
  • 9