简体   繁体   中英

how to resolve python error “not all arguments converted while string formatting”

When i execute below program

import MySQLdb
cn = MySQLdb.connect(host="localhost", user="root", passwd="mysqlroot", 
db="sv_data")
cursor = cn.cursor()
cursor.execute("select addressline1, zipcode from sv_address where zipcode = '10011'")
for (addressline1, zipcode) in cursor:
print(addressline1, zipcode)
cursor.close()
cn.close()

it works fine. However when i try to add a parameter in query, like below

import MySQLdb
 cn = MySQLdb.connect(host="localhost", user="root", passwd="****",     
db="sv_data")
cursor = cn.cursor()

a="10011"
cursor.execute("select addressline1, zipcode from sv_address where zipcode = 
%s", (a))
for (addressline1, zipcode) in cursor:
 print(addressline1, zipcode)

cursor.close()
cn.close()

getting error ProgrammingError: not all arguments converted during string formatting

can you please advise how to fix this. I tried various options. zipcode is varchar field in mysqldb

You are not passing the argument. you are rather giving it a string.

Try this.

cursor.execute("select addressline1, zipcode from sv_address where zipcode = %s" % a )

The best way to do is to separate your arguments and sql_query

_sql = "select addressline1, zipcode from sv_address where zipcode = {0}"
cursor.execute(_sql.format(a))

I believe the issue is that cursor is reading (a) as just a string and sees multiple values in it that aren't being converted( 1, 0, 0, 1, 1 ). So if you add a comma like so:

cursor.execute("select addressline1, zipcode from sv_address where zipcode = %s", (a,))

I believe that will work properly.

For instance, look at this function and the outcome:

In [28]: def t(arg):
    ...:     print(type(arg))
    ...:     

In [29]: t(('a'))
<class 'str'>

The argument isn't being read as a tuple, it's being read as a string.

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