如何安装Gorm
go get -u gorm.io/gorm
go get -u gorm.io/driver/sqlite
GORM 目前支持 MySQL、SQLServer、PostgreSQL、SQLite.
连接mysql数据库
进行一次简单的查询
会出现如下报错
因为
GORM 使用结构体名的 蛇形命名 作为表名。对于结构体 User,根据约定,其表名为 users
可以在gorm.Config中添加如下配置
gorm.Config{NamingStrategy: schema.NamingStrategy{
SingularTable: true, // 使用单数表名
}}
还有另一种方式
type Tabler interface {
TableName() string
}
// TableName 会将 User 的表名重写为 `user`
func (User) TableName() string {
return "user"
}
在一般情况下结构体的列名和数据库的字段是不对照的 使用下面的方式来解决
type User struct {
Id int64 `json:"id,omitempty"`
Name string `json:"name,omitempty"`
FollowCount int64 `json:"follow_count,omitempty"`
FollowerCount int64 `json:"follower_count,omitempty"`
IsFollow bool `json:"is_follow,omitempty"`
}