导入数据库连接的数据,这里我直接使用const常量,在企业级项目中应该去读取配置文件
const (
host = "localhost"
port = 5432
user = "postgres"
password = "ROOT"
dbname = "demo1"
)
导入pg的依赖,记得前面有一个 "_"
import (
_ "github.com/lib/pq"
)
连接数据库代码
func InitSql() {
// 构建连接字符串
connStr := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
// 连接到数据库
db, err := sql.Open("postgres", connStr)
if err != nil {
panic(err)
}
defer db.Close()
// 尝试连接并检查错误
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Println("Successfully connected to the PostgreSQL database!")
queryUserInformation(db)
}
控制台输出
Successfully connected to the PostgreSQL database!
那就表示连接成功了