当前位置:网站首页>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-30 22:04:00 【Game programming】
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 tomlimport ( "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 TomlConfigfunc 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 = 3306Mysql 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 mysqlimport ( "fmt" "gorm.io/driver/mysql" "gorm.io/gorm" "gorm.io/gorm/logger" "learn-gin/config/toml")var _db *gorm.DBfunc 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_entityimport "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 servicesimport ( "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 reqtype 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 servicesvar ( TestServ = &Test{} StudentServ = &StudentImpl{})stay app/controllers Add... Below student_controller.go file .

The code is as follows :
package controllersimport ( "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 controllersvar ( TestCtrl = &TestController{} StudentCtrl = &StudentController{})stay app/router Add under directory student_router.go file .

The code is as follows :
package routerimport ( "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 routerimport "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 .

author : Swordsman a Liang _ALiang
Game programming , A game development favorite ~
If the picture is not displayed for a long time , Please use Chrome Kernel browser .
边栏推荐
- 《Dynamic Routing Between Capsules》论文学习总结
- Jupyterbook clear console output
- Starting from pg15 xid64 ticket skipping again
- RP prototype resource sharing - shopping app
- [introduction to MySQL] the first conversation · first time in the "database" Mainland
- Why does the computer speed slow down after vscode is used for a long time?
- 程序员女友给我做了一个疲劳驾驶检测
- 艾芬医生事件解析
- Stimulate new kinetic energy to develop digital economy in multiple places
- 模板方法模式介绍与示例
猜你喜欢

《Dynamic Routing Between Capsules》论文学习总结

Introduction and example of template method mode

Analysis of PostgreSQL storage structure

1-2 安装并配置MySQL相关的软件

Look at the top 10 capabilities of alicloud cipu

Rethink healthy diet based on intestinal microbiome

PyTorch量化实践(1)

Anaconda下安装Jupyter notebook

B_ QuRT_ User_ Guide(31)

5g demand in smart medicine
随机推荐
机器学习中如何使用数据集?
The programmer's girlfriend gave me a fatigue driving test
Vite2 is compatible with lower versions of chrome (such as Sogou 80). Some grammars requiring higher versions are processed through polyfills
去中心化交易所系统开发技术原理丨数字货币去中心化交易所系统开发(说明案例)
Bloom filter
1-7 path module
PyTorch量化实践(2)
看阿里云 CIPU 的 10 大能力
The Three Musketeers: One for All!
1-18 create the most basic express server & API module for creating routes
How to realize the center progress bar in wechat applet
PostgreSQL存储结构浅析
Do a scrollbar thinking
Docker installing MySQL
Apache服务器OpenSSL升级
周少剑,很少见
将Nagios监控信息存入MySQL
The Jenkins download Plug-in can't be downloaded. Solution
【BSP视频教程】BSP视频教程第19期:单片机BootLoader的AES加密实战,含上位机和下位机代码全开源(2022-06-26)
Introduce an online platform for multi omics integration and network visual analysis