Golang初始化MySQL数据库方法浅析
作者:三杯温开水 时间:2024-01-16 23:49:20
安装依赖
主要这边还需要安装两个依赖,gorm
、viper
,具体的可以访问他们的官网(Gorm官网地址 Viper Github地址)
初始化配置
在根目录下打开终端执行:
go mod init 项目名称 (例如: go mod init demo )
安装依赖
go get github.com/jinzhu/gorm 或 go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql
go get github.com/spf13/viper
创建文件
创建一个yml文件(application.yml
)
#server:
# post: 8888
datasource:
driverName: mysql
host: # 端口地址
port: # 端口号
database: # 数据库名称
username: # 账号
password: # 密码
charset: utf8
在目录下创建一个common包,包下再创建一个database.go文件,内部写一个初始化数据库,建议拆分出来,这样拼接的方式有利于项目在不同环境下进行快速的更改配置。
package common
import (
"fmt"
// 看清楚引入包,包的差异存在方法差异
"github.com/jinzhu/gorm"
"github.com/spf13/viper"
)
// 用大写声明(可以全局访问)
var DB *gorm.DB
// 创建数据库连接池
func InitDB() *gorm.DB {
driverName := viper.GetString("datasource.driverName")
host := viper.GetString("datasource.host")
port := viper.GetString("datasource.port")
database := viper.GetString("datasource.database")
username := viper.GetString("datasource.username")
password := viper.GetString("datasource.password")
charset := viper.GetString("datasource.charset")
args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true",
username,
password,
host,
port,
database,
charset)
db, err := gorm.Open(driverName, args)
if err != nil {
fmt.Println("fail err mysql", err.Error())
}
// gorm 自动创建表,需要放入model层中的模型,比如 User{}
db.AutoMigrate(User{})
// 进行赋值 否则会空指针
DB = db
return db
}
// 获取DB的示例
func GetDB() *gorm.DB {
return DB
}
main函数执行
在根目录下创建一个main文件(唯一)
,在这个环境我们需要做做一个初始化配置文件的操作,在main中优先加载这个config,然后才是初始化数据库,顺序不能错哈,因为数据库的连接信息在yml文件中,所以不要将顺序搞错。
package main
import (
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
"github.com/spf13/viper"
"go-gin-vue/common"
"os"
)
func main() {
InitConfig()
// 尝试连接数据库
db := common.InitDB()
// 延迟关闭
defer db.Close()
r := gin.Default()
// 加载路由
r = CollectRouter(r)
// 监听的端口
// 可以在yml中定义server端口并且使用yml文件中定义的端口
// port := viper.GetString("server.port")
if port != "" {
panic(r.Run(":" + port))
}
r.Run(":9000") // 测试端口 9000 上启动服务
}
// 初始化config文件
func InitConfig() {
workDir, _ := os.Getwd()
// 读取的文件名
viper.SetConfigName("application")
// 读取的文件类型
viper.SetConfigType("yml")
// 读取的路径
viper.AddConfigPath(workDir + "/config")
err := viper.ReadInConfig()
if err != nil {
panic("")
}
}
来源:https://blog.csdn.net/weixin_47024018/article/details/127445628
标签:GoLang,Go,初始化,数据库
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
MySQL数据库中对前端和后台进行系统优化
2009-01-04 13:39:00
浅谈Python中的函数(def)及参数传递操作
2023-01-20 20:13:54
centos7使用rpm安装mysql5.7的教程图解
2024-01-21 20:07:09
![](https://img.aspxhome.com/file/2023/4/72704_0s.jpg)
Mysql中where与on的区别及何时使用详析
2024-01-21 03:31:19
![](https://img.aspxhome.com/file/2023/3/65293_0s.png)
python3 判断列表是一个空列表的方法
2022-02-03 09:40:07
uniapp开发打包成H5部署到服务器的详细步骤
2024-04-10 16:20:19
![](https://img.aspxhome.com/file/2023/1/136701_0s.jpg)
关于Python3 lambda函数的深入浅出
2023-01-12 09:12:41
Opencv实现二维直方图的计算及绘制
2023-07-18 23:34:52
![](https://img.aspxhome.com/file/2023/6/59646_0s.jpg)
MySQL中数据查询语句整理大全
2024-01-15 21:59:05
python Tkinter是什么
2022-07-26 08:31:51
![](https://img.aspxhome.com/file/2023/5/133805_0s.png)
对tf.reduce_sum tensorflow维度上的操作详解
2023-01-07 14:10:28
Python远程SSH库Paramiko详细操作
2022-08-14 18:38:09
Python 格式化输出字符串的方法(输出字符串+数字的几种方法)
2021-05-03 21:25:00
Python开发虚拟环境使用virtualenvwrapper的搭建步骤教程图解
2022-02-08 00:33:29
![](https://img.aspxhome.com/file/2023/5/107945_0s.png)
流动的线条 —— 中国汉字书法之美
2009-10-30 18:15:00
![](https://img.aspxhome.com/file/UploadPic/200910/30/1-79s.jpg)
在ASP.NET 2.0中操作数据之四十:自定义DataList编辑界面
2023-07-07 04:45:20
![](https://img.aspxhome.com/file/2023/0/75550_0s.png)
pytorch中dataloader 的sampler 参数详解
2023-09-16 21:00:13
oracle关键字作为字段名使用方法
2024-01-18 07:57:59
MSSQL数据库排序规则如何更改
2023-07-01 11:09:58
google 的设计原则和LOGO手绘
2008-05-20 12:16:00
![](https://img.aspxhome.com/file/UploadPic/20085/20/2008520122313977s.gif)