I'm trying to iterate through a Python list to have multiple queries in MySQL, but the "%s" parameter is including quotes and I get only zeros (0) in my query (when I know I should get a different number).
The code:
def export_data():
infos = [
'Conta Corrente Itau',
'Cartao Itau Master',
'Cartao Itau VISA',
'Carteira'
]
chart_of_accounts = list(infos)
for account in chart_of_accounts:
cnx = mariadb.connect(user='root', password='', database='base_completa')
cursor = cnx.cursor()
params = (account, account)
query = """
SELECT Y, M,(@total := @total + Fluxo) AS ValorTotal
FROM (
SELECT year(data) AS Y, month(data) AS M,
(
SUM(IF(Credito="%s", valor, 0))-
SUM(IF(Debito="%s", valor, 0))
) AS Fluxo
FROM ledger
GROUP BY YEAR(DATA), MONTH(DATA)
) AS T,
(SELECT @total:=0) AS n;
""" % (params)
cursor.execute(query)
rows = cursor.fetchall()
desc = cursor.description
lista = [dict(itertools.izip([col[0] for col in desc], row))
for row in rows]
cnx.commit()
print account
print json.dumps(lista)
return lista
results = export_data()
I also tried:
cursor.execute(query, (chart_of_accounts[account] for account in chart_of_accounts))
But I still get zero. I think it is including the quotes inside the parameter so the query it is making is:
SUM(IF(Credito=""Conta Corrente Itau"", valor, 0))
EDIT: (Actually, it was not passing the list element to the query, so it was querying:
SUM(IF(Credito="%s", valor, 0))
But I don't know for sure.
It seems to work fine other than that, as my "checking prints" are giving me the expected results.
RESOLVED:
When having more than one parameter in the MySQL Query, I found 1 thread that answered my question: add a "params" variable that aggregates the parameters.
params = (account, account)
And then add % (params) after the end of the query (""")
Updated the code with a functioning one. Still don't know if that is good practice or the best way to do it, but it works.