python通过sqlachemy连接postgre进行模糊查询报错,代码如下:
from sqlalchemy import create_engine
engine = create_engine("postgresql://postgres@localhost:5432/postgres")
conn = engine.connect()
sql = "select * from 表名 where 字段名 like '张三%'"
res = conn.excute(sql)
错误信息:
TypeError: 'dict' object does not support indexing?
解决方法:
- 方法一:
SQLAlchemy有一个用于包装文本的Text函数,该函数转义了SQL
from sqlalchemy import create_engine, text
res = conn.excute(text(sql))
- 方法二:
采用 %% 当作 %, 因为%在python中用作字符串格式,因此若要实现 % 当作通配符的作用是,需要使用 双%。
sql = "select * from 表名 where 字段名 like '张三%%'"
res = conn.excute(sql)
参考文献: