Golang 在 CentOS 上怎么配置数据库连接:MySQL 与 PostgreSQL 实战说明
时间:2026-08-25 | 作者:宇宙开黑者 | 阅读:0在CentOS上搞定Golang的数据库连接,前提是先把对应的数据库驱动安排上。下面以MySQL和PostgreSQL为例,走一遍完整的流程。
先看MySQL。第一步自然是安装驱动,终端里执行:
go get -u github.com/go-sql-driver/mysql
搞定之后,写个main.go文件把连接逻辑跑通。直接上代码:
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
// 数据库连接字符串
dsn := "username:password@tcp(localhost:3306)/dbnamecharset=utf8mb4&parseTime=True&loc=Local"
// 连接数据库
db, err := sql.Open("mysql", dsn)
if err != nil {
panic(err)
}
defer db.Close()
// 测试数据库连接
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Println("Connected to the MySQL database!")
}
注意把username、password、localhost、3306和dbname换成实际的值。然后跑起来:
go run main.go
如果一切正常,终端里会输出“Connected to the MySQL database!”。
接下来是PostgreSQL,流程类似,但驱动和连接串的格式不一样。先装驱动:
go get -u github.com/lib/pq
然后写main.go:
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
func main() {
// 数据库连接字符串
dsn := "user=username password=password dbname=dbname sslmode=disable host=localhost port=5432"
// 连接数据库
db, err := sql.Open("postgres", dsn)
if err != nil {
panic(err)
}
defer db.Close()
// 测试数据库连接
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Println("Connected to the PostgreSQL database!")
}
同样,把username、password、localhost、5432和dbname替换成你自己的信息。运行:
go run main.go
成功的话,输出就是“Connected to the PostgreSQL database!”。
免责声明:文中图文均来自网络,如有侵权请联系删除,心愿游戏发布此文仅为传递信息,不代表心愿游戏认同其观点或证实其描述。
相关文章
更多-
- CentOS 上 Python 版本怎么选:先保系统,再看项目与稳定性
- 时间:2026-08-25
-
- CentOS 下如何配置 Golang 并发模型
- 时间:2026-08-25
-
- CentOS 上安装 Python 需要哪些依赖?从基础环境到编译与项目隔离一次讲清
- 时间:2026-08-25
-
- CentOS 系统部署 Golang 应用,安全配置该从哪些环节下手
- 时间:2026-08-25
-
- Golang 在 CentOS 上如何搭建调试环境
- 时间:2026-08-25
-
- CentOS 下如何调试运行 Python 脚本:从 print 到 pdb 的实用选择
- 时间:2026-08-25
-
- CentOS 中 Golang 依赖库怎么安装
- 时间:2026-08-25
-
- 在 CentOS 上部署 Go 项目,这些细节要先处理好
- 时间:2026-08-25
精选合集
更多大家都在玩
大家都在看
更多-
- 糖尿病完全不能吃糖吗
- 时间:2026-09-15
-
- 蚂蚁庄园小课堂2026年9月16日最新题目答案
- 时间:2026-09-15
-
- 小鸡答题今天的答案是什么2026年9月16日
- 时间:2026-09-15
-
- 蚂蚁庄园每日答题答案2026年9月16日
- 时间:2026-09-15
-
- 以下哪种粮食是酿造绍兴黄酒的主要原料 蚂蚁庄园今日答案9月16日
- 时间:2026-09-15
-
- 劝学名句“及时当勉励,岁月不待人”出自哪位诗人 蚂蚁庄园今日答案9.16
- 时间:2026-09-15
-
- 蚂蚁庄园今天答题答案2026年9月16日
- 时间:2026-09-15
-
- 蚂蚁庄园答题今日答案2026年9月16日
- 时间:2026-09-15
