当前位置:网站首页>Go language learning notes - Gorm usage - database configuration, table addition | web framework gin (VII)
Go language learning notes - Gorm usage - database configuration, table addition | web framework gin (VII)
2022-06-28 12:52:00 【Swordsman a Liang_ ALiang】
Catalog
Learning notes , Where is where .
Next to the previous article :Go English learning notes - Add file download tool | Web frame Gin( 6、 ... and )_ Swordsman a Liang _ALiang The blog of -CSDN Blog
I have supplemented the tool classes that I thought of temporarily , Start the connection and use of the database .
Starting from this article, I will gradually increase the database related operations .
Project address :github Address
Dependent installation
First install what you need gorm and mysql drive .
The installation instructions are as follows :
go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql
Mmysql To configure
Modify the configuration file toml_config.go, increase mysql Related configuration .
For specific usage, please refer to :Go English learning notes - Configuration file usage 、 Log configuration | Web frame Gin( Two )_ Swordsman a Liang _ALiang The blog of -CSDN Blog _config.toml
toml_config.go The adjusted code of the file is as follows :
package toml
import (
"fmt"
"github.com/spf13/viper"
)
type TomlConfig struct {
AppName string
Log LogConfig
Mysql MysqlConfig
}
// Log storage address
type LogConfig struct {
Path string
Level string
}
// Log storage address
type MysqlConfig struct {
Host string
User string
Password string
DbName string
Port int64
}
var c TomlConfig
func init() {
// Set file name
viper.SetConfigName("config")
// Set file type
viper.SetConfigType("toml")
// Set file path , Can be more viper It will search in order of setting order
viper.AddConfigPath(".")
viper.AutomaticEnv()
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("fatal error config file: %s", err))
}
viper.Unmarshal(&c)
}
func GetConfig() TomlConfig {
return c
}
You can see the increase MysqlConfig Structure .
The configuration file config.toml File increase mysql Corresponding configuration , Revised as follows :
appName = "learn-gin"
[log]
level = "debug"
path = "logs/learn.log"
[mysql]
host = "xx.xx.xx.xx"
user = "root"
password = "xxxxxx"
dbName = "test-c"
port = 3306
Mysql initialization
Add the database connection initialization code ,mysql_init.go File added to config/mysql Next , Here's the picture .

mysql_init.go The document code is as follows :
package mysql
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"learn-gin/config/toml"
)
var _db *gorm.DB
func init() {
username := toml.GetConfig().Mysql.User // account number
password := toml.GetConfig().Mysql.Password // password
host := toml.GetConfig().Mysql.Host // Database address , It can be Ip Or domain name
port := toml.GetConfig().Mysql.Port // Database port
Dbname := toml.GetConfig().Mysql.DbName // Database name
timeout := "10s" // Connection timeout ,10 second
// Under the splice dsn Parameters , dsn The format can refer to the syntax above , Use here Sprintf Dynamic splicing dsn Parameters , Because the general database connection parameters , We are all saved in the configuration file , Parameters need to be loaded from the configuration file , Then joining together dsn.
dsn := fmt.Sprintf("%s:%[email protected](%s:%d)/%s?charset=utf8&parseTime=True&loc=Local&timeout=%s", username, password, host, port, Dbname, timeout)
var err error
// Connect MYSQL, get DB Type instance , Used for subsequent database read and write operations .
_db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
})
if err != nil {
panic(" Failed to connect to database , error=" + err.Error())
}
sqlDB, _ := _db.DB()
// Set database connection pool parameters
sqlDB.SetMaxOpenConns(100) // Set the maximum number of connections to the database connection pool
sqlDB.SetMaxIdleConns(20) // The maximum number of free connections allowed in the connection pool , without sql The number of connections that the task needs to execute is greater than 20, More than connections will be closed by the connection pool .
}
func GetDB() *gorm.DB {
return _db
}
Can pass GetDB Method to get _db To operate .
add table
We create a test table in the database , At present, you can also use gorm Migrate a table structure to the database , Let's create... For the time being . surface ( Table name :student) The structure is as follows :

Add... Under the project folder db_entity Folder stores table entities . Here's the picture :

student_entity.go The code is as follows :
package db_entity
import "time"
type Student struct {
Id int32 `json:"id" gorm:"column:id;primary_key;AUTO_INCREMENT;comment:'id'"`
Name string `json:"name" gorm:"column:name;type:varchar(255);comment:' name '"`
Age int64 `json:"age" gorm:"column:age;comment:' Age '"`
Content string `json:"content" gorm:"column:content;type:varchar(255);comment:' describe '"`
UpdateTime time.Time `json:"update_time" gorm:"column:update_time"`
DelFlag int64 `json:"del_flag" gorm:"column:del_flag;comment:' Delete logo '"`
}
// Custom table name
func (Student) TableName() string {
return "student"
}
Adding a table
Add the interface according to the optimized project structure , Reference resources :Go English learning notes - Project specification structure adjustment | Web frame Gin( 3、 ... and )_ Swordsman a Liang _ALiang The blog of -CSDN Blog
stay app/services Add under directory student._service.go file , The code is as follows :
package services
import (
"learn-gin/app/pojo/req"
"learn-gin/app/pojo/rsp"
"learn-gin/config/log"
"learn-gin/config/mysql"
"learn-gin/db_entity"
"time"
)
type StudentService interface {
AddStudent(req *req.StudentAddReq)
}
type StudentImpl struct {
}
// Add student
func (t StudentImpl) AddStudent(req *req.StudentAddReq) rsp.ResponseMsg {
log.Logger.Info(" Add student parameters :", log.Any("StudentReq", req))
_db := mysql.GetDB()
var _student db_entity.Student
_student.Name = req.Name
_student.Age = req.Age
_student.Content = req.Content
_student.UpdateTime = time.Now()
_student.DelFlag = 0
_db.Create(&_student)
return *rsp.SuccessMsg(" Add success ")
}
among app/pojo/req Add a request structure under StudentAddReq, stay app/pojo/req Add under directory student_request.go file .
The code is as follows :
package req
type StudentAddReq struct {
Name string `json:"name"`
Age int64 `json:"age"`
Content string `json:"content"`
}
stay app/services/service.go increase student service object , The code is as follows :
package services
var (
TestServ = &Test{}
StudentServ = &StudentImpl{}
)
stay app/controllers Add... Below student_controller.go file .

The code is as follows :
package controllers
import (
"encoding/json"
"github.com/gin-gonic/gin"
"learn-gin/app/pojo/req"
"learn-gin/app/services"
"learn-gin/config/log"
"net/http"
)
type StudentController struct {
}
func (s StudentController) StudentAddOne(context *gin.Context) {
var addStudentReq req.StudentAddReq
log.Logger.Info("StudentAddOne Interface ")
// Put the front end through json The data binding is stored in this entity class ,BindJSON() Can also be used
if err := context.ShouldBindJSON(&addStudentReq); err != nil {
log.Logger.Panic(" Parameter exception ")
}
if _, err := json.Marshal(addStudentReq); err != nil {
log.Logger.Panic(" Parameter parsing exception ")
}
_rsp := services.StudentServ.AddStudent(&addStudentReq)
context.JSON(http.StatusOK, _rsp)
}
stay app/controllers/controllers.go File increase student_controller Control layer objects in .
The code is as follows :
package controllers
var (
TestCtrl = &TestController{}
StudentCtrl = &StudentController{}
)
stay app/router Add under directory student_router.go file .

The code is as follows :
package router
import (
"github.com/gin-gonic/gin"
"learn-gin/app/controllers"
)
func StudentRouter(r *gin.Engine) {
r.POST("/student/addOne", controllers.StudentCtrl.StudentAddOne)
}
stay app/router/router.go Lower bound StudentRouter.
package router
import "github.com/gin-gonic/gin"
func InitRouter(r *gin.Engine) {
// Test route
TestRouter(r)
// Student routing
StudentRouter(r)
}
Test interface
When the code is complete , Let's test the new interface in the table .

OK, Let's look at the table data .

No problem .
Summary
I didn't expect that it was written 30 The article ,gorm Still studying , I will write all the table operations later .

边栏推荐
- 哪一个证券公司最好最安全 怎么办理开户最安全
- 命名空间和作用域
- Unity WebGL移动端去除警告
- Is tongdaxin stock software reliable? Is it safe to trade stocks on it?
- Jerry's wif interferes with Bluetooth [chapter]
- 易观分析《2022年中国银行业隐私计算平台供应商实力矩阵分析》研究报告正式启动
- Digital twin energy system, creating a "perspective" in the low-carbon era
- FineReport安装教程
- Unity Editor Extension Foundation, GUI
- arcgis pro 可以实现直连postgresql,编辑图层要素吗
猜你喜欢

ASP. NET CORE Study08

From simplekv to redis

Login interface accesses and clears the token
![BUUCTF:[WUSTCTF2020]朴实无华](/img/0f/a7973d3f7593f2464e48609e27d7bd.png)
BUUCTF:[WUSTCTF2020]朴实无华

百度APP 基于Pipeline as Code的持续集成实践

Finereport installation tutorial
Siyuan official paid synchronization Guide

Après avoir échoué à l'examen d'entrée à l'Université de technologie de Harbin, vous devez rester à l'Université en tant que « chercheur » après avoir obtenu votre diplôme.

ASP.NET CORE Study04

关于IP定位查询接口的测评Ⅰ
随机推荐
Given two points and a point with a middle scale, find the coordinates of the point
Is tongdaxin stock software reliable? Is it safe to trade stocks on it?
数字孪生能源系统,打造低碳时代“透视”眼
Understand leveldb write operation
登录接口存取token,清除token
哪一个证券公司最好最安全 怎么办理开户最安全
从SimpleKV到Redis
June 28, 2022 Daily: Lecun's latest paper: the road to autonomous machine intelligence
Here comes Wi Fi 7. How strong is it?
I ² C. SMBus, pmbus relationships
华泰证券手机app下载 怎么办理开户最安全
ASP.NET CORE Study01
From jsonpath and XPath to spl
杰理之wif 干扰蓝牙【篇】
Unity Editor Extension Foundation, guilayout
mysql数据库扫盲,你真的知道什么是数据库嘛
Ipetronik data acquisition equipment and softing q-vision software are committed to ADAS test scheme
js 期约与异步函数 Promise
Après avoir échoué à l'examen d'entrée à l'Université de technologie de Harbin, vous devez rester à l'Université en tant que « chercheur » après avoir obtenu votre diplôme.
Matplotlib_Study01