简体   繁体   中英

How do I use variables as attribute names when using python mysql connector

I am trying to use variables in a python function to try and retrieve attributes with mysql connector

It seems to work only when I specify the name of the attribute in the query itself

def insert(ids, added_attribute):
    insert = ''
    if len(ids) > 0:
        #insert scpecified attributes wanted
        insert += ' AND (%s = %s' %(added_attribute, ids[0])
        #for loop for more than one specified specific attribute
        for id_index in range(1, len(ids)):
            insert += ' OR %s = %s' %(added_attribute, ids[id_index])
        insert += ')'#close parenthesis on query insert
    return insert

def get(name, attributes = 0, ids = []):
    cursor = conn.cursor()

    #insert specific ids
    insert = insert(ids, "id")

    query = 'SELECT %s FROM (TABLE) WHERE (name = %s%s)'

    cursor.execute(query, (attributes, name, insert))

    data = cursor.fetchall()
    cursor.close()
    return data

I keep getting null as a return value

Try this...

query = 'SELECT {} FROM (TABLE) WHERE (name = {}{})'
cursor.execute(query.format(attributes, name, insert))

{} is replacing %s here and to call the variables you just need to add .format() with the vars you want inserted in order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM