Go语言连接PostgreSQL报错求助:getaddrinfow找不到指定类
Go连接PostgreSQL出现"dial tcp: lookup tcp/5432,: getaddrinfow: The specified class was not found"错误排查
错误信息
panic: dial tcp: lookup tcp/5432,: getaddrinfow: The specified class was not found. goroutine 1 [running]: main.main() C:/Dev/Digitalent/scalable-web-service-with-golang/go-sql/main.go:35 +0x23a exit status 2
原代码
package main import ( "database/sql" "fmt" _ "github.com/lib/pq" ) const ( host = "localhost" port = 5432 username = "postgres" password = "*********" dbName = "db-go-sql" ) var ( db *sql.DB err error ) func main() { psqlURL := fmt.Sprintf("host=%s port=%d, user=%s, password=%s "+"dbname=%s sslmode=disable", host, port, username, password, dbName) db, err = sql.Open("postgres", psqlURL) if err != nil { panic(err) } defer db.Close() err = db.Ping() if err != nil { panic(err) } fmt.Println("Connection to postgresql established") }
问题根源
错误出在连接字符串的格式上:github.com/lib/pq驱动要求连接参数的键值对之间用空格分隔,但代码里给port、user、password后面加了逗号,导致驱动把port的值解析成了5432,,进而错误地将tcp/5432,当作主机名去做DNS解析,最终触发getaddrinfow错误。
修正后的代码
只需要去掉连接字符串里的逗号即可:
package main import ( "database/sql" "fmt" _ "github.com/lib/pq" ) const ( host = "localhost" port = 5432 username = "postgres" password = "*********" dbName = "db-go-sql" ) var ( db *sql.DB err error ) func main() { // 去掉参数之间的逗号,用空格分隔 psqlURL := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host, port, username, password, dbName) db, err = sql.Open("postgres", psqlURL) if err != nil { panic(err) } defer db.Close() err = db.Ping() if err != nil { panic(err) } fmt.Println("Connection to postgresql established") }
补充说明
如果习惯用URI格式的连接字符串,也可以这样写(注意格式正确):
psqlURL := fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=disable", username, password, host, port, dbName)
内容的提问来源于stack exchange,提问作者Bayu Aji
相关产品推荐
相关产品推荐

