2
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

4

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

this does help out a bit. but it is not fetching the data from the database? is something else wrong too?
probably related to getting the rowcount before executing the query?
1

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():
    ....

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.