03_xorm

一、安装

	go get github.com/go-xorm/xorm




使用示例 

// 结构体名称对应数据库表名
type Smscode struct {
   Id         int    `xorm:"pk autoincr" json:"id"`
   Code       string `xorm:"varchar(255)" json:"code"`
   Phone      string `xorm:"varchar(255)" json:"phone"`
   CreateTime int    `xorm:"int" json:"create_time"`
}





import (
  _ "github.com/go-sql-driver/mysql"
 "github.com/go-xorm/xorm"
)
conn := "root:password@tcp(127.0.0.1:port)/database?charset=utf8mb4"
eg, err := xorm.NewEngine("mysql", conn)
if err != nil {
   fmt.Println("链接失败")
}
fmt.Println("链接成功。。。")
eg.ShowSQL(true)
 
//映射结构体,好像没什么卵用
err = eg.Sync2(new(Smscode))
if err != nil {
   fmt.Println("映射失败")
}

smsCode := Smscode{Code: "123456", Phone: "15700000000", CreateTime: 12345678910}
fmt.Println(smsCode)
result, err := eg.InsertOne(smsCode)
if err != nil {
   fmt.Println("插入失败")
}
fmt.Println(result)





//事物

eg, err := xorm.NewEngine("mysql", conn)
defer eg.Close()
sess:=eg.NewSession()
err:=sess.Begin()

sess执行sql语句

sess.Rollback()
sess.Commit()











条件查询

var sms model.SmsCode

// eg,err:= xorm.NewEngine("mysql",[connectString])

_,err:=eg.Where("phone= ? and code = ?",phone,code).Get(&sms)




	

1.1、service 封装

	tool/OrmEngine.go

	import (

		"github.com/go-xorm/xorm"

		_ "github.com/go-sql-driver/mysql"

	)

	type Orm struct{

		*xorm.Engine

	}

	var DbEngine *Orm

	func OrmEngine(cfg *Config) (*Orm,error){

		database : = cfg.Database

		conn:=database.User+":"+database.Password + "@tcp("+database.Host+":"+database.Port+")/"+database.Database+"?charset=utf8"

		engine,err :=xorm.NewEgine("mysql",conn)

		if err !=nil {

			return nil,err

		}

		engine.ShowSQL(true)

		err :=engine.Sync2(new(model.SmsCode))

		orm :=new(Orm)

		orm.Engine =engine

		DbEngine = orm

		return orm,nil

	}

1.2、model调用

	model/SmsCode.go

	type SmsCode struct {

		Id int64 `xorm:"pk autoincr" json:"id"`

		Phone string  `xorm:"varchar(11)"  json:"phone"`

		CreateTime int64 `xorm:"bigint" json:"create_time"`

	}

1.3、dao/MemberDao.go

		type MemberDao struct{

			*tool.Orm

		}

	func (md *MemberDao) InsertCode(sms model.SmsCode) int64{

		result,err :=md.InsertOne(&sms)

		//返回的是插入的id

		return result

	}




1.4、service/MemberService.go	

	当前时间 time.Now().Unix()

	smsCode:=model.SmsCode(Phone:phone,Code:code,CreateTime:time.Now().Unix())

	memberDao:=dao.MemberDao{}

	res:=memberDao.InsertCode(smsCode)