Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python and MySQLdb: substitution of table resulting in syntax error

I need to dynamically change tables and variables from time to time, so I wrote a python method like this:

    selectQ ="""SELECT * FROM  %s WHERE %s = %s;""" 
    self.db.execute(selectQ,(self.table,self.columnSpecName,idKey,))
    return self.db.store_result()

However this results in a syntax error exception. I tried debugging it so I printed the variables in the method and filled them in manually, and that worked. So I am not sure what I am doing wrong ?

Is it because I try to use a substitute for a table ?

Also how do I debug mysqldb so it prints the substituted query as a string ?

like image 512
Lucas Kauffman Avatar asked Feb 22 '12 11:02

Lucas Kauffman


2 Answers

Parameter substitution in the DB API is only for values - not tables or fields. You'll need to use normal string substitution for those:

selectQ ="""SELECT * FROM  %s WHERE %s = %%s;""" % (self.table,self.columnSpecName)
self.db.execute(selectQ,(idKey,))
return self.db.store_result()

Note that the value placeholder has a double % - this is so that it's left alone by the initial string substitution.

like image 189
Daniel Roseman Avatar answered Sep 18 '22 00:09

Daniel Roseman


Here is a full working example

def rtnwkpr(tick, table, col):

    import MySQLdb as mdb
    tickwild = tick + '%'       
    try:
        con = mdb.connect(host, user, password, db);
        cur = con.cursor()
        selectq = "SELECT price FROM %s WHERE %s LIKE %%s;" % (table, col)
        cur.execute(selectq,(tickwild))
        return cur.fetchall()           
like image 37
Peter Rogers Avatar answered Sep 19 '22 00:09

Peter Rogers