python - 使用 python mysql 连接器时如何使用变量作为属性名称

标签 python mysql mysql-connector-python

我正在尝试在 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/

相关文章:

python - PySpark:根据与另一列中的字符串匹配的字典值创建新列

python - python字符串项赋值的替代方案

mysql - 显示 31 天的休假状态

mysql - 设置和清除 MySQL 中存储为整数的多个位

python - mySQLdb 连接返回截断的输出

python mysql.connector 连接断开时写入失败停滞 30 秒

python - 对哈希 (MD5) 电子邮件地址进行取消哈希处理

python - 子进程中断管道和文件忙

mysql 使用相同数字的名称计数

python - MySQL 连接器无法使用表别名