位置:首页 > Go > Golang 在 CentOS 上怎么配置数据库连接:MySQL 与 PostgreSQL 实战说明

Golang 在 CentOS 上怎么配置数据库连接:MySQL 与 PostgreSQL 实战说明

时间:2026-08-25  |  作者:宇宙开黑者  |  阅读:0

在CentOS上搞定Golang的数据库连接,前提是先把对应的数据库驱动安排上。下面以MySQL和PostgreSQL为例,走一遍完整的流程。

Golang在CentOS上的数据库连接怎么配置

先看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!")
}

注意把usernamepasswordlocalhost3306dbname换成实际的值。然后跑起来:

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!")
}

同样,把usernamepasswordlocalhost5432dbname替换成你自己的信息。运行:

go run main.go

成功的话,输出就是“Connected to the PostgreSQL database!”。

免责声明:文中图文均来自网络,如有侵权请联系删除,心愿游戏发布此文仅为传递信息,不代表心愿游戏认同其观点或证实其描述。

相关文章

更多

精选合集

更多

大家都在玩

热门话题

大家都在看

更多