How to insert query result in mysql with python

Asked

Viewed 1,461 times

2

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

The code is this.

Temperature and humidity are already returning, but not saved in the database the values.

# 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 !!!")
  • Rename the title of your question so that its name specifies the content. Tip: "How to insert the result of a query into the database". It’s just a suggestion :)

  • What a mistake Vinicius ?

  • does not save the result to the database.

  • 1

    You’re passing the strings 'temp', 'umid' us VALUES of INSERT should not be the variables temp and umid

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)

0

Viniciius,

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

Then all the code inside the 3 double quotes is ignored.

Try to change yours:

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

for:

cursor.execute("INSERT INTO temperatura (temp, umidade) VALUES ('temp', 'umid')")
  • Rubico, this will insert the strings 'temp' and 'umid' in the bank. I suspect that the OP really wants to insert the values of the variables temp and umid.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.