How to insert query result in mysql with python

I need to insert in the database the result of this query through the temperature medulla.

The code is this.

The temperature and humidity are already returning, but it does not save the values in the database.

# Carrega as bibliotecas
#!/usr/bin/python
# -*- coding: utf-8 -*- 
import MySQLdb
import Adafruit_DHT
import RPi.GPIO as GPIO
import time


db = MySQLdb.connect(host="localhost", user="root", passwd="root", db="sensores")
cursor = db.cursor()

# Define o tipo de sensor
sensor = Adafruit_DHT.DHT11
#sensor = Adafruit_DHT.DHT22

GPIO.setmode(GPIO.BOARD)

# Define a GPIO conectada ao pino de dados do sensor
pino_sensor = 4

# Informacoes iniciais
print ("*** Lendo os valores de temperatura e umidade");

while(1):
   # Efetua a leitura do sensor
   umid, temp = Adafruit_DHT.read_retry(sensor, pino_sensor);
   # Caso leitura esteja ok, mostra os valores na tela
   if umid is not None and temp is not None:
     print ("Temperatura = {0:0.1f}  Umidade = {1:0.1f}\n").format(temp, umid);
     cursor.execute("""INSERT INTO temperatura (temp, umidade) VALUES ('temp', 'umid')""")
     db.commit()
     print ("Aguarda 5 segundos para efetuar nova leitura...\n");
     time.sleep(5)
   else:
     # Mensagem de erro de comunicacao com o sensor
     print("Falha ao ler dados do DHT11 !!!")
Author: Vinicius Fernandes, 2016-02-16

2 answers

Change Your Line:

cursor.execute("""INSERT INTO temperatura (temp, umidade) VALUES ('temp', 'umid')""")

For this one:

sql = "INSERT INTO temperatura (temp, umidade) VALUES ('%s', '%s')" % (temp, umid)
cursor.execute(sql)
 1
Author: Renato Tavares, 2016-02-19 16:01:00

Viniciius,

When you use three double quotes in a row in python, you are making a documentation string, or docstring.

Then all code that is within the 3 double quotes is ignored.

Try to swap yours:

cursor.execute("""INSERT INTO temperatura (temp, umidade) VALUES ('temp', 'umid')""")

For:

cursor.execute("INSERT INTO temperatura (temp, umidade) VALUES ('temp', 'umid')")
 0
Author: Rubico, 2016-03-11 14:28:25