How to insert query result in mysql with python

1

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

The code is this.

Temperature and humidity are already returning, but the values are not saved 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 !!!")
    
asked by anonymous 16.02.2016 / 19:15

2 answers

1

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)
    
19.02.2016 / 17:01
0

Vinicius,

When you use three consecutive double quotation marks in python, you are doing a string of documentation, or docstring .

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

Try changing your:

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

To:

cursor.execute("INSERT INTO temperatura (temp, umidade) VALUES ('temp', 'umid')")
    
11.03.2016 / 15:28