golang 连接 postgres 15 用户名:root 密码:KXGNEYpkyxuXXfRB 请写出代码
下面是一个示例代码,可以连接到 PostgreSQL 数据库,用户名为 root,密码为 KXGNEYpkyxuXXfRB:
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
func main() {
// 构造连接字符串
connStr := "postgres://root:KXGNEYpkyxuXXfRB@localhost:5432/mydb?sslmode=disable"
// 连接数据库
db, err := sql.Open("postgres", connStr)
if err != nil {
panic(err)
}
defer db.Close()
// 测试连接
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Println("Connected to PostgreSQL!")
}
其中,connStr 是连接字符串,它包含了数据库的连接信息,例如用户名、密码、主机名、端口号、数据库名等。sql.Open() 方法会根据此连接字符串连接到 PostgreSQL 数据库。
如果连接成功,db.Ping() 方法会返回一个 nil 错误,否则会返回相应的错误信息。
原文地址: https://www.cveoy.top/t/topic/bSHf 著作权归作者所有。请勿转载和采集!