1.mysql连接配置
package daoimport ("fmt""gorm.io/driver/mysql""gorm.io/gorm""gorm.io/gorm/logger"
)var DB *gorm.DB// 连接数据库,启动服务的时候,init方法就会执行
func init() {username := "root" //账号password := "123456" //密码host := "127.0.0.1" //数据库地址,可以是IP或者域名port := 3306 //数据库端口Dbname := "ry" //数据库名dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", username, password, host, port, Dbname)db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Info),})if err != nil {panic("连接数据库失败,原因:" + err.Error())}DB = db
}
2.数据库操作 业务类
package daoimport "log"type User struct {//主键//ID int32//通过在字段后面的标签来定义golang字段和表字段的关系//例如:`gorm:"column:username"` 标签说明含义是:Mysql表的列名(字段名)为 usernameUserName string `gorm:"column:user_name"`NickName string `gorm:"column:nick_name"`//CreateTime int64 `gorm:"column:create_time"` //创建时间,时间戳
}// 映射表名
func (user User) TableName() string {return "sys_user"
}func SaveUser(user *User) {//新增err := DB.Create(user).Errorif err != nil {log.Println("新增用户失败,原因:", err)}
}func GetUserById(id string) User {var user Usererr := DB.Where("id = ?", id).First(&user).Errorif err != nil {log.Println("查询用户失败,原因:", err)}return user
}
3.接口请求
package controllerimport ("gin/dao""github.com/gin-gonic/gin"//"time"
)func SaveUser(context *gin.Context) {//创建用户的实例user := &dao.User{UserName: "苏冬雪",NickName: "123456",//CreateTime: time.Now().UnixMilli(),}//执行保存dao.SaveUser(user)context.JSON(200, user)
}
4.接口请求
5.数据库