tags:

views:

289

answers:

3
def dispcar ( self, reg ):
       print ("The car information for '%s' is: "), (reg)
       numrows = int(self.dbc.rowcount) #get the count of total rows
       self.dbc.execute("select * from car where reg='%s'") %(reg)
       for x in range(0, numrows):
        car_info = self.dbc.fetchone()
        print row[0], "-->", row[1]

the above code gives this error:

self.dbc.execute("select * from car where reg='%s' " %(reg)
TypeError: unsupported operand type(s) for %: 'long' and 'str'

can anyone please help me understand why am i getting this error?

FYI: reg is a raw_input var i input from user in the function getitem and pass the reg var as an argument to this function.

+2  A: 

I think this line simply has the parens in the wrong place:

self.dbc.execute("select * from car where reg='%s'") %(reg)

You are using % on the result of execute(), and reg.

Change it to:

self.dbc.execute("select * from car where reg='%s'" % reg)

or

self.dbc.execute("select * from car where reg='%s'", reg)

depending on whether it will do the param substitution for you.

Ned Batchelder
this does help out a bit. but it is not fetching the data from the database? is something else wrong too?
amit
probably related to getting the rowcount before executing the query?
ChristopheD
+2  A: 

You got the brackets wrong:

self.dbc.execute("select * from car where reg=%s" , (reg,))

Any particular reason you are looping using fetchone (in this ugly loop with a range based on a rowcount which will probably be zero as you get it before you execute the query)?

Just do

for car_info in self.dbc.fetchall():
    ....
ChristopheD
+2  A: 

This confuses just about everyone who works with MySQLDB. You are passing arguments to the execute function, not doing python string substitution. The %s in the query string is used more like a prepared statement than a python string substitution. This also prevents SQL injection as MySQLDB will do the escaping for you. As you had it before (using % and string substitution), you are vulnerable to injection.

  1. Don't use quotes. MySQLDB will put them there (if needed).
  2. Use a , instead of a %. Again, you are passing a tuple as an argument to the execute function.

    self.dbc.execute("select * from car where reg=%s" , (reg,))

mluebke