[ XORM数据库基础[golang] ]


官方文档

安装

  1. 安装 xorm.io/xorm
  2. 安装 Mysql驱动

基本使用连接

  1. xorm连接数据库, 根据User结构体生成表
package main

import (
    "fmt"
    "time"

    _ "github.com/go-sql-driver/mysql"
    "xorm.io/xorm"
)

type User struct {
    Id       int64
    Age      int
    Password string    `xorm:"varchar(125)"`
    Created  time.Time `xorm:"created"`
    Updated  time.Time `xorm:"updated"`
}

type User struct {
    Id       int64
    Age      int
    Email    string    `xorm:"varchar(25) notnull unique 'usr_name' comment('邮箱')"`
    Password string    `xorm:"varchar(125)"`
    Created  time.Time `xorm:"created"`
    Updated  time.Time `xorm:"updated"`
}

func (u *User) BeforeInsert() {
    u.Created = time.Now()
    u.Updated = time.Now()
}

func main() {
    engine, err := xorm.NewEngine("mysql", "root:chenhaifeng@tcp(47.120.55.99:3306)/go_tenant?charset=utf8")
    engine.ShowSQL(true)
    engine.TZLocation, _ = time.LoadLocation("Asia/Shanghai")
    if err != nil {
        fmt.Println("数据库连接失败")
    }
    fmt.Println(engine)

    err = engine.Sync(new(User))
    if err != nil {
        fmt.Println("数据库创建失败")
    }

user := User{
    Age:      16,
    Email:    "123@qq.com",
    Password: "123456",
}
插入单个1.返回:受影响的行数
insertCount, _ := engine.Insert(&user)
if insertCount >= 1 {
    fmt.Println("插入成功")
}

插入多个2.
var userList []User
userList = append(userList, User{Age: 13, Email: "1@qq.com", Password: "124"})
userList = append(userList, User{Age: 12, Email: "2@qq.com", Password: "123"})
insertCount, _ = engine.Insert(userList)
if insertCount >= 1 {
    fmt.Printf("插入数量:%d", insertCount)
}

修改1
updateCount, _ := engine.ID(1).Update(&User{Age: 32, Email: "3@qq.com", Password: "123"})
if updateCount >= 1 {
    fmt.Printf("更新的数量:%d", updateCount)
}

// 删除1: id为1而且email=3@qq.com的
engine.ID(1).Delete(&User{Email: "3@qq.com"})

// 原生
res, _ := engine.Exec("update user set age = ? where id = ?", 12, 2)
fmt.Println(res)

}