python - 使用 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 可以读取的函数呢?我想做的甚至可能吗?提前致谢。
解决方案
也许令人惊讶的是,您不应该让数据库替换处理表名和列名。它试图引用它们,就好像它们是字段一样,这是错误的。
sql = "SELECT %s FROM %s WHERE %s=%%s" % (column_name,table_name,where_clause)
...
cursor.execute(sql, (where_value,))
推荐阅读
- sql - 如何在 SQL Server 的查询中创建日期表?
- flutter - 在同一页面中使用两个 BLoC 并在第二个 BLoC 中传递第一个 BLoC 的状态
- java - 如何从服务器向客户端发送大量数据集
- javascript - 在 react-select 组件中隐藏旋转按钮
- spring - AWS SQS 消费者不消费消息
- python - 使用lxml Python同时为单个对象检索多个嵌套语句
- c - C 代码在假定运行 scanf 行时停止
- javascript - Leaflet - 避免在 javascript 中重叠标签的方法
- google-cloud-platform - GCP:资源名称与 URL:不一致的匹配
- java - Sonarqube 抱怨 for 循环中未使用的变量