可以使用PGX驱动程序连接到PostgreSQL数据库,但可以使用终端
从代码中,
代码Bellow输出以下内容:
2022/06/21 16:01:07无法连接到DB:无法连接到'host = local -Host = localhost user = postgres database = local':local':服务器错误(fatal:stisent:esident:stisent:stisent:用户“ Postgres”(SQLSTATE 28000))退出状态1
import (
"context"
"log"
"github.com/jackc/pgx/v4"
)
func main() {
dbCtx := context.Background()
db, err := pgx.Connect(
dbCtx,
"postgres://postgres:smashthestate@localhost:5432/local",
)
if err != nil {
log.Fatalf("Failed to connect to db: %v\n", err)
}
defer db.Close(dbCtx)
// do stuff with db...
}
从终端
进行了身份验证,但是从终端可以连接到DB。例如,此命令如果使用相同的参数运行(DB名称,用户名,密码)将提供正确的输出:
PSQL -D LOCAL -U POSTGRES -W -C'SELECT * From Import;'
>
注释
- 命令正常工作,即使用户发送的既不是
root
也不是postgres
。 - 本地连接的身份验证方法设置为
Trust
内部pg_hba.conf
:
local all all trust
那么,我在这里缺少什么?为什么命令行的一切正常,但无法从代码中使用?
From code
The code bellow outputs the following:
2022/06/21 16:01:07 Failed to connect to db: failed to connect to 'host=localhost user=postgres database=local': server error (FATAL: Ident authentication failed for user "postgres" (SQLSTATE 28000)) exit status 1
import (
"context"
"log"
"github.com/jackc/pgx/v4"
)
func main() {
dbCtx := context.Background()
db, err := pgx.Connect(
dbCtx,
"postgres://postgres:smashthestate@localhost:5432/local",
)
if err != nil {
log.Fatalf("Failed to connect to db: %v\n", err)
}
defer db.Close(dbCtx)
// do stuff with db...
}
From terminal
However, connection to db is possible from terminal. For example, this command if run with the same parameters (db name, user name, password) will give correct output:
psql -d local -U postgres -W -c 'select * from interest;'
Notes
- Command works correctly even if sent by user that is neither
root
norpostgres
. - Authentication method for local connection is set to
trust
insidepg_hba.conf
:
local all all trust
So, what am I missing here? Why everything works fine from the command line but doesn't work from code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
GO的默认值与PSQL不同。如果没有给出主机名,请默认使用LocalHost,而PSQL默认为使用UNIX域插座。
要指定一个Unix域套接字要走,您需要奇怪地做才能在URI验证中生存下来:
尽管结束可能需要更像
?host =%2FVAR%2fvar%2frun%2fpostgresql
,取决于不同关于如何配置服务器。但是,为什么要指定不需要的密码?那将引起毫无意义的混乱。
Go's defaults are different from psql's. If no hostname is given, Go defaults to using localhost, while psql defaults to using the Unix domain sockets.
To specify a Unix domain socket to Go, you need to do it oddly to get it to survive URI validation:
Though the end might need to be more like
?host=%2Fvar%2Frun%2Fpostgresql
, depending on how the server was configured.But why are you specifying a password which is not needed? That is going to cause pointless confusion.