Python and MySQLdb: substitution of table resulting in syntax error

前端 未结 4 1229
日久生厌
日久生厌 2020-11-27 23:33

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         


        
相关标签:
4条回答
  • 2020-11-28 00:03

    You'll have to use string substitution to add the table and column names, the driver will only handle parameters.

    Ed: NM, Daniel answered faster and more completely

    0 讨论(0)
  • 2020-11-28 00:16

    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()           
    
    0 讨论(0)
  • 2020-11-28 00:20

    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.

    0 讨论(0)
  • 2020-11-28 00:21

    Did you mean to write:

    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)
    

    and this is just a mistake with string formatting?

    Btw why do you write explicit SQL for this kind of work? better use magical sqlalchemy for python sql manipulation..

    0 讨论(0)
提交回复
热议问题