首页 > 解决方案 > 包含 SQL 查询的字符串中的变量 - Python

问题描述

我有一个字符串设置如下:

sql_string = ( """ select * from schema.table where column1 like '%object%' and column2 = '%s' """)%(x)

不幸的是,当我运行脚本时,出现以下错误:

TypeError: not enough arguments for format string

有什么方法可以让我的查询字符串中有一个变量吗?我怀疑查询的 column1 部分中的百分号是导致问题的原因。

谢谢!

标签: pythonsql

解决方案


您可以使用其他 % 转义 %:

sql_string = ( """ select * from schema.table where column1 like '%%object%%' and column2 = '%s' """)%(x)

推荐阅读