首页 > 解决方案 > 使用 Python 函数将字符串传递给 pymysql 游标

问题描述

我正在编写一个脚本,该脚本将使用 pymysql 和一个简单的 SELECT 语句从数据库中提取数据。我将多次运行这个语句,所以我希望通过将它放在一个函数中并将列名、表名、where 子句和值作为参数传递给函数来简化事情。

def retrieve_value_from_db(connection,column_name,table_name,where_clause,where_value):
    with connection:
        with connection.cursor() as cursor:
            sql = "SELECT %s FROM %s WHERE %s=%s"
            logging.debug(cursor.mogrify(sql,(column_name,table_name,where_clause,where_value)))
            cursor.execute(sql,(column_name,table_name,where_clause,where_value))
            result = cursor.fetchone()
        connection.commit()
    return result

但是调用下面的函数会返回以下错误

retrieve_value_from_db(connection,"last_name","mother_table","id","S50000")

pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''mother_table' WHERE 'id'='S50000'' at line 1")

Cursor.execute 似乎正在读取字符串的引号部分,这导致了编程错误。那么如何将字符串参数传递给 cursor.execute 可以读取的函数呢?我想做的甚至可能吗?提前致谢。

标签: pythonmysqlpymysql

解决方案


也许令人惊讶的是,您不应该让数据库替换处理表名和列名。它试图引用它们,就好像它们是字段一样,这是错误的。

sql = "SELECT %s FROM %s WHERE %s=%%s" % (column_name,table_name,where_clause)
...
cursor.execute(sql, (where_value,))

推荐阅读