package dbhelper
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
/// 连接数据库得到
func GetConn() (*gorm.DB,error) {
db,err :=gorm.Open("mysql","root:123456@(192.168.0.100:3306)/mytest?charset=utf8mb4&parseTime=True&loc=Local")
return db,err
}
type User struct {
Uid uint `gorm:"column:uid;primary_key;AUTO_INCREMENT"`
UserName string
Age uint
Bj string
}
package createtable
import (
"GinMysql/dbhelper"
"GinMysql/model"
_ "github.com/jinzhu/gorm/dialects/mysql"
"log"
)
func init(){
var user model.User
var userinfo model.UserInfo
db,err := dbhelper.GetConn()
if err!=nil{
log.Panicln("连接数据库出错:",err)
}
db.SingularTable(true) // 不设置表名为复数
// 数据迁移 到Mysql
db.AutoMigrate(&user)
db.AutoMigrate(&userinfo)
}
package main
import (
// 引用 createtable 调用init方法
_ "GinMysql/createtable"
"GinMysql/route"
)
func main(){
engin:= route.SetUpRoute()
engin.Run(":8090")
}
type Mycount struct {
Usercount uint
}
// 关于Gorm执行原生SQL
// **********语句字段要小写************
// ***********查询用db.Raw,其他用db.Exec
// *********** 字段大小写要对应上 **************
// *************** 注意要 defer rows.Close()
var Mycount Mycount
rows,_:= db.Debug().Raw("select Count(1) as Usercount from Users").Rows()
defer rows.Close()
for rows.Next() {
rows.Scan(&Mycount.Usercount)
}
var users []User
// 查询 执行用Scan 和Find 一样
db=db.Raw("select uid,user_name,age from Users").Scan(&users)
//db=db.Raw("select uid,user_name,age from Users").Find(&users)
fmt.Println("Users",users)
// 更新和删除.插入用 Exec
db= db.Exec("update Users set user_name='def' where uid=?",1)
fmt.Println("更新了",db.RowsAffected,"条数据")
db= db.Exec("delete from Users where uid=?",2)
fmt.Println("更新了",db.RowsAffected,"条数据")
return int32(Mycount.Usercount)
var mycont int
// count 使用
db.Debug().Model(&Myaaa{}).Where("id<?",10).Count(&mycont)
// 更新
db.Debug().Model(&Myaaa{}).Update(my)
// 分页 Offset 跳过 Order 排序
db.Limit(2).Offset(1).Order("id desc").Where("id>?",0).Find(&bbb)
// 删除
db.Delete(my)