How to check if a variable received a new python value?

Asked

Viewed 53 times

-2

I have a Thread from a function that inserts data into the database and another Thread that every second receives a new value for a variable, however it may be the same previous value only "new". I wanted to know how I make the thread expect this new value and every time I receive this new value do the Insert in the bank. A part of my code :

def EnviaBanco():
    global nomepessoa  # nomepessoa é uma variavel global em outra função, esse nomepessoa esta  dentro de um  while que  esta recebendo um novo valor  a  todo momento
    global cam
    Conectando banco de dados
    try:
        mydb = mysql.connector.connect(
          host="localhost",
          user="teste",
          password="teste102030",
          database="teste"
        )
        print ("Conexão realizada com sucesso")
    except:
        print("[ERROR] verifique a conexão com banco  de dados")
    
    while True:
    " if nomeatual recebeu um novo valor: "
        time.sleep(10.0)
        #Inicializando banco
        mycursor = mydb.cursor()
        #Inserindo dados
        sql = ("INSERT INTO teste (nomes, camera) VALUES (%s,%s)")
        #Executando os dados  e comitando
        mycursor.execute(sql,(nomepessoa, cam))
        mydb.commit()
        print("Dados inseridos com sucesso")
'''
  • The logic of your function is a little strange. Creating a cursor inside the loop is not a good practice. Avoid using global. I will answer below in a generic way, because I do not know how you take the data.

  • 1) Why have a thread just for insertion? 2) If really necessary, read about the queue data structure (Queue).

2 answers

0

In a generic way do something like:

class ConexaoBanco():
   _instance = None
   def __init__(self):
       pass

   @staticmethod
   def get_instance():
       if ConexaoBanco._instance == None:
          ConexaoBanco._instance = ConexaoBanco()
       return ConexaoBanco._instance

    def conecta(self):
        # conecta no banco
        self.mydb = mysql.connector.connect(
                                            host="localhost",
                                            user="teste", 
                                            password="teste102030",
                                            database="teste"
                                          )
        self.mycursor = self.mydb.cursor()

    def getCursor(self):
        return self.myCursor()

    def close(self):
        self.mycursor.close()
         self.mydb.close()


def processaNome():
    # Pega cursor
    mydb = ConexaoDB().get_instance()
    mycursor = mydb.getCursor()
    #
    lastNome = None
    while True:
        # Pega o nome
        nomePessoa = ... # aqui o processo de pegar o nome.
        if nomePessoa != lastNome:
            sql = ("INSERT INTO teste (nomes, camera) VALUES (%s,%s)")
            mycursor.execute(sql, (nomePessoa, cam))
            lastNome = nomePessoa
        time.sleep(10)

Note: the Connected Bank class can be improved. But the important thing is how to keep the last name picked.

Still, I believe that you do not need each of them, ie take name and insert in the bank, in a thread different.

  • 1

    Thank you very much, you gave me an idea of how I can do in my code, thank you

-1

There is the Queue module and the Queue class that allows you to do this safely.

Communication between threads is technically complicated, don’t try to create your own schema from scratch.

In fact, if you can avoid threading, use processes with a pipe between them. It is even worth using a local TCP/IP connection between two processes to be better isolated.

Browser other questions tagged

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