Use go xorm to manipulate mysql's method instances
- 2020-07-21 08:20:50
- OfStack
In golang to achieve database operations, a relatively easy way is to use XORM, xorm is a simple and powerful Go language ORM library, through which database operations can be very simple. In xorm, there can be multiple ORM engines simultaneously, one ORM engine is called Engine, and one Engine1 generally corresponds to only one database.
Connection pool configuration for golang
This initializes a global xorm. Engine object, which is generated by calling xorm. Engine and is passed as a parameter in many other API. Here we need to understand the meaning of the three parameters set here:
SetMaxIdleConns()
SetMaxOpenConns()
SetConnMaxLifetime
go xorm to operate mysql
It's useful. Here it is:
package main
import (
"fmt"
"github.com/go-xorm/xorm"
"github.com/go-xorm/core"
_ "github.com/go-sql-driver/mysql"
)
// Corresponding to the database tablename Must be student
// perform mysql , the corresponding field is xxx,yyy,zzz; You can also omit it, by default mysql Field is id,username,address
type Student struct {
Id int `xorm:"INT(11) 'xxx'"`
Username string `xorm:"VARCHAR(64) 'yyy'"`
Address string `xorm:"VARCHAR(256) 'zzz'"`
}
func main() {
engine, err := xorm.NewEngine("mysql", "root@/taoge?charset=utf8") // dbname is taoge
if err != nil{
fmt.Println(err)
return
}
// The following Ping Can don't
// if err := engine.Ping(); err != nil{
// fmt.Println(err)
// return
// }
//engine.ShowSQL(true) // According to SQL The implementation of the , Easy to debug and analyze
engine.SetTableMapper(core.SnakeMapper{})
st1 := new(Student)
st1.Username = "taoge"
st1.Address = "China"
affected, err := engine.Insert(st1)
fmt.Println(affected)
st2 := new(Student)
result,err := engine.Where("xxx=?", 1).Get(st2)
fmt.Println(result)
fmt.Println(st2.Username)
fmt.Println(st2.Address)
}
Create database:
CREATE TABLE `student` (
`xxx` int(11) NOT NULL AUTO_INCREMENT,
`yyy` varchar(64) NOT NULL,
`zzz` varchar(256) NOT NULL ,
PRIMARY KEY (`xxx`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
Operation results:
[
1
true
taoge
China
conclusion