Python and MySQLdb: table replacement resulting in syntax error

I need to change tables and variables dynamically from time to time, so I wrote the python method as follows:

    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. I tried debugging it to print the variables in the method and populate them manually, and it worked. So I'm not sure what I'm doing wrong?

Is it because I'm trying to use table replacement?

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

+5
source share
4 answers

Parameter substitution in the database API is intended only for values ​​- not tables or fields. You will need to use the usual string replacement for them:

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

, double % - , .

+10

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()           
+1

, .

: NM, .

0

:

selectQ = """SELECT * FROM %s WHERE %s = %s;""" % (self.table,self.columnSpecName,idKey) #maybe the idkey should be self.idkey? don't know the rest of the code

self.db.execute(selectQ)

?

, SQL ? sqlalchemy python sql..

-3

All Articles