G
G
German Jet2015-01-31 07:49:10
MySQL
German Jet, 2015-01-31 07:49:10

How to write a sql query with parameters correctly?

date = '31/01/2015'
date_format = '%%d/%%m/%%Y'

Request:
rows = db.session.execute("SELECT * FROM weather WHERE DATE_FORMAT(putdate, %s) = %s", (date_format, date))

Gives an error message:
AttributeError: 'tuple' object has no attribute 'keys'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
pcdesign, 2015-01-31
@GeraJet

I tried myself

date = '31/01/2015'
date_format = '%d/%m/%Y'
g.cur.execute("""SELECT * FROM `per` WHERE DATE_FORMAT(`date_sf`, %s) = %s""",
                    (date_format, date))
rows = g.cur.fetchall()
print(rows)

That's how it works.
Well, even in relation to alchemy.
This is how it works:
date = '01/01/2015'                                                           
date_format = '%d/%m/%Y'                                                      
sql = """SELECT * FROM `users` WHERE DATE_FORMAT(`date`, '%s') = '%s' """ % (date_format, date)                                                       
rows = db.session.execute(sql)

And there is another way.
IMHO, the most correct:
from sqlalchemy import text
rows = db.session.execute(text("SELECT * FROM `users` WHERE  DATE_FORMAT(`date`, :df) = :date "), 
{"df": '%d/%m/%Y', "date": '01/01/2015'})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question