Write the result of a variable in the mysql database using python passed as parameter

6

I have a database in mysql that contains a table with multiple expressions. I can extract the expressions through procedure , solve them, but when I want to return the calculation value to the bank with another procedure , this value is not saved. Here is 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')")
    
asked by anonymous 26.06.2015 / 04:43

1 answer

1

From what I understand, your difficulty is in passing variables to your SQL query, right? The execute command has a params that receives a tuple / list or dictionary. Here you associate indexes or variable names with 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 one 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 does what it has to do (as you did not post your code, there is no way we can help you if it has a problem ).

    
26.06.2015 / 18:35