Golang:使用PostgreSQL模式进行连接

时间:2018-07-21 18:54:22

标签: postgresql go database-schema

我正在寻找连接并查询PostgreSQL。但是我只想连接到特定的 Schema

根据文档( JDBC ),我们可以使用

jdbc:postgresql://localhost:5432/mydatabase?searchpath=myschema

更新,从9.4开始,您可以使用新的currentSchema参数指定网址,如下所示:

jdbc:postgresql://localhost:5432/mydatabase?currentSchema=myschema

但是我无法通过 golang SQL驱动程序来做到这一点;

根据文档,我们也可以使用SET search_path TO myschema,public; ,但是我只想在初始化期间声明一次,但是我认为对于每次新连接都需要执行一次。

我也在使用以下代码,请帮助我确定要传递给此参数的正确参数,以便仅与模式连接

db, err := sql.Open("postgres", `dbname=`+s.settings.Database+
` user=`+s.settings.Username+` password=`+s.settings.Password+
` host=`+s.settings.Url+` sslmode=disable`) 

添加currentSchema=myschemasearchpath=myschema无效!

有没有办法我只能连接到GO中的特定数据库架构

2 个答案:

答案 0 :(得分:3)

将Search_path设置为正确,然后执行一次。即:

db, err := sql.Open("postgres",
    "host=localhost dbname=Test sslmode=disable user=postgres password=secret")
if err != nil {
   log.Fatal("cannot connect ...")
}
defer db.Close()
db.Exec(`set search_path='mySchema'`)

rows, err := db.Query(`select blah,blah2 from myTable`)
...

答案 1 :(得分:3)

您应将search_path=myschema添加到dataSourceName

P.S。最好使用fmt.Sprintf("host=%s port=%d dbname=%s user=%s password='%s' sslmode=disable search_path=%s", ...)代替``+``