You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在LangChain中连接PostgreSQL并指定自定义schema?

解决LangChain SQLAgent切换PostgreSQL自定义schema的问题

你遇到的no parameters defined错误,是因为直接在PostgreSQL连接地址后拼接search_path=my_schema的方式不正确——PostgreSQL的连接参数里没有直接的search_path项,需要通过options参数传递运行时配置。以下是几种可行的解决方法:

方法一:修改连接字符串,通过options参数指定search_path

将search_path作为PostgreSQL运行时参数,通过URL编码后拼接到连接字符串的查询参数中:

connection_string = "postgresql://username:password@host:port/dbname?options=-c%20search_path%3Dmy_schema"

这里的%20是空格的URL编码,%3D是等号的URL编码,确保参数能被正确解析。

方法二:创建SQLAlchemy引擎时指定connect_args

在初始化SQLAlchemy引擎时,通过connect_args直接传递search_path配置,这种方式更直观,无需URL编码:

from sqlalchemy import create_engine
from langchain.sql_database import SQLDatabase

engine = create_engine(
    "postgresql://username:password@host:port/dbname",
    connect_args={"options": "-c search_path=my_schema"}
)
db = SQLDatabase(engine)

之后用这个db对象初始化SQLAgent即可。

方法三:连接后执行SET语句切换schema

如果上述两种方式不适用,也可以在数据库连接建立后,手动执行SQL语句切换schema:

from langchain.sql_database import SQLDatabase

# 先创建默认连接的数据库对象
db = SQLDatabase.from_uri("postgresql://username:password@host:port/dbname")
# 执行切换schema的语句
db.run("SET search_path TO my_schema;")

后续SQLAgent的所有操作都会在my_schema下执行。

内容的提问来源于stack exchange,提问作者blackzzz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 15:27:37