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.
3 Answers 3
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.
- Don't use quotes. MySQLDB will put them there (if needed).
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,))
Comments
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.
2 Comments
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():
....