Save the result of a variable to the Mysql database using python passed as parameter

Asked

Viewed 1,044 times

6

I have a database on mysql which contains a table with several expressions. I can extract the expressions through a procedure, solve them, but when I want to return the value of the calculation to the bank with another procedure, this value is not saved. Follow the code below:

    # mysql = MySQLdb.connect(host = "localhost", user = "client", passwd = "123456", db = "sist_dist")
    mysql = MySQLdb.connect('192.168.252.30','client','123456','sist_dist')
    mysql_cursor = mysql.cursor()
    mysql_cursor.execute("call retira_exp('mangaba')")

    linha_expressao = mysql_cursor.fetchone()


    if linha_expressao=="":
        sys.exit()

    expressao_banco = linha_expressao[1]
    id_expressao = linha_expressao[0]


    resultado = eval(expressao_banco)

    print  resultado

    mysql_cursor = mysql.cursor()
    mysql_cursor.execute("CALL entrega_res('id_expressao','resultado')")
  • @mgibsonbr you can help?

  • Fernando, I don’t think he gets any notification, he needs to interact with the question to make it happen. Only then do you use the @.

  • first time using, I’m kind of lost in this kind of thing.

  • and Voce Florida could give me a boost?

  • Sorry, this far beyond my knowledge, the best you can do is wait patiently.

  • 1

    still quarreled.

Show 1 more comment

1 answer

1

From what I understand, your difficulty is in passing variables to your SQL query, right? The command execute has a parameter params which receives a tuple/list or dictionary. In it you associate indexes or variable names to their actual values:

valores = (id_expressao, resultado)
mysql_cursor.execute("CALL entrega_res(%s,%s)", valores)

Or:

valores = {
    "id_expressao":id_expressao,
    "resultado":resultado,
}
mysql_cursor.execute("CALL entrega_res(%{id_expressao}s,%{resultado}s)", valores)

(in my opinion, the first is shorter and simpler; use the second only if you need to use the same value twice in the same query)

This should pass the values correctly to your call. From there, you need to make sure that the stored Procedure entrega_res do what you have to do (since you didn’t post your code, there’s no way we can help you with it if it has any problems).

  • Brigadão Marcelo, now running filet, but is not recording the information staying as NULL. CREATE DEFINER=root@localhost PROCEDURE entrega_res( IN id_temp INT, resultado_temp VARCHAR(400) ) BEGIN UPDATE tb_expressoes SET result = resultado_temp, time_delivery = NOW() where id = id_temp; END

Browser other questions tagged

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