Skip to content Skip to sidebar Skip to footer

Python Mysql Fetch Query

def dispcar ( self, reg ): print ('The car information for '%s' is: '), (reg) numrows = int(self.dbc.rowcount) #get the count of total rows

Solution 1:

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

Solution 2:

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.

Solution 3:

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

forcar_infoinself.dbc.fetchall():
    ....

Post a Comment for "Python Mysql Fetch Query"