1

I have two queries in SQL which are the following:

q1 = select date_hour from table

And, the second query is:

q2 = select date(date_hour) from table

The only difference between these queries is the string date_hour and date(date_hour). SO, I tried parameterising my query in the following manner:

q1 = select %s from table
cur.execute(q1,'date')
cur.execute(q1,'date(date_hour)')

However, this throws an error which is:

not all arguments converted during string formatting

Why am I getting this error? How can I fix it?

3 Answers 3

1

Change the comma in cur.execute to %

Change this:

q1 = "select %s from table"
cur.execute(q1,'date')
cur.execute(q1,'date(date_hour)')

to:

q1 = "select %s from table"
cur.execute(q1 % 'date')
cur.execute(q1 % 'date(date_hour)')
Sign up to request clarification or add additional context in comments.

Comments

0

It's unclear wich sql library you're using but assuming it uses the Python DB API:

Sql parameters are typically used for values, not columns names (while this is possible using stored procedures).

It seems you're confused between string formatting in python and sql parametized queries.

While %s can be used to format a string (see formatting strings) this is not the way to set sql parameters.

See this response to use sql parameters in python.

By the way i can't see anything wrong with this simple code:

cursor=cnx.curor()
query="select date_hour from table"
cursor.execute(query)
query="select date(date_hour) from table"
cursor.execute(query)

2 Comments

I don't want the same query to be written twice. The two queries are exactly same except for one difference.That is why, i want to parameterize them.
As i said parameters are meant to be used for values not columns name. Still if you really insist on using the same string this should do the trick: cur.execute('select %s from table1' % 'date_hour')
0

Change your code to something like this:

q1 = "select %s from table" cur.execute(q1,['date']) cur.execute(q1,['date(date_hour)'])

Check this

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.