我正在尝试在 python 函数中使用变量来尝试使用 mysql 连接器检索属性
它似乎仅当我在查询本身中指定属性名称时才起作用
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
我不断得到 null 作为返回值
最佳答案
试试这个...
query = 'SELECT {} FROM (TABLE) WHERE (name = {}{})'
cursor.execute(query.format(attributes, name, insert))
{} 在这里替换 %s 并调用变量,您只需添加 .format() 以及您想要按顺序插入的变量。
关于python - 使用 python mysql 连接器时如何使用变量作为属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57233959/