简体   繁体   中英

String replacement in SQL Query using Python

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?

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)')

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)

Change your code to something like this:

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

Check this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM