阅读量:1
在CentOS上集成Go语言与数据库,可以按照以下步骤进行:
1. 安装Go语言
首先,你需要在CentOS上安装Go语言。以下是安装步骤:
使用包管理器安装
sudo yum install golang
手动安装
- 下载Go语言安装包:
wget https://golang.org/dl/go1.17.6.linux-amd64.tar.gz
- 解压安装包:
sudo tar -C /usr/local -xzf go1.17.6.linux-amd64.tar.gz
- 配置环境变量:
编辑 ~/.bashrc 或 /etc/profile 文件,添加以下内容:
export PATH=$PATH:/usr/local/go/bin
然后使配置生效:
source ~/.bashrc
- 验证安装:
go version
2. 安装数据库
CentOS上常用的数据库有MySQL、PostgreSQL等。以下以MySQL为例:
使用包管理器安装MySQL
sudo yum install mysql-server
启动并启用MySQL服务:
sudo systemctl start mysqld
sudo systemctl enable mysqld
运行安全脚本:
sudo mysql_secure_installation
使用包管理器安装PostgreSQL
sudo yum install postgresql-server postgresql-contrib
启动并启用PostgreSQL服务:
sudo systemctl start postgresql
sudo systemctl enable postgresql
创建数据库和用户:
sudo -u postgres psql
CREATE DATABASE mydb;
CREATE USER myuser WITH ENCRYPTED PASSWORD 'mypassword';
GRANT ALL PRIVILEGES ON mydb.* TO myuser;
\q
3. 在Go中连接数据库
以下是一个简单的Go程序,演示如何连接MySQL数据库:
安装MySQL驱动
go get -u github.com/go-sql-driver/mysql
编写Go代码
创建一个名为 main.go 的文件,内容如下:
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
// 连接数据库
dsn := "myuser:mypassword@tcp(127.0.0.1:3306)/mydb"
db, err := sql.Open("mysql", dsn)
if err != nil {
panic(err.Error())
}
defer db.Close()
// 测试连接
err = db.Ping()
if err != nil {
panic(err.Error())
}
fmt.Println("Successfully connected to the database!")
}
运行程序
go run main.go
如果一切正常,你应该会看到输出:
Successfully connected to the database!
4. 集成其他数据库
对于其他数据库(如PostgreSQL),你需要安装相应的Go驱动,并修改连接字符串。例如,连接PostgreSQL的代码如下:
安装PostgreSQL驱动
go get -u github.com/lib/pq
编写Go代码
修改 main.go 文件,内容如下:
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
func main() {
// 连接数据库
dsn := "user=myuser password=mypassword dbname=mydb sslmode=disable"
db, err := sql.Open("postgres", dsn)
if err != nil {
panic(err.Error())
}
defer db.Close()
// 测试连接
err = db.Ping()
if err != nil {
panic(err.Error())
}
fmt.Println("Successfully connected to the database!")
}
运行程序
go run main.go
通过以上步骤,你可以在CentOS上成功集成Go语言与数据库。
以上就是关于“如何在CentOS上集成Go语言与数据库”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm