使用go语言中的xrom和Sync2创建并添加数据
package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql"//必须导入,手动添加
"xorm.io/core"
"xorm.io/xorm"
)
func main() {
engine, err := xorm.NewEngine("mysql", "root:123@/test6?charset=utf8") // dbname是taoge
if err != nil {
fmt.Println(err)
return
}
if err := engine.Ping();err !=nil{
fmt.Println(err,"数据库连接失败!")
return
}
defer engine.Close()
fmt.Println("数据库连接成功!")
engine.SetMapper(core.GonicMapper{})
//建立表字段
engine.Sync2(new(PresonTable))
presonEmpty,err := engine.IsTableEmpty(new(PresonTable))
if err !=nil{
panic(err.Error())
}
if presonEmpty{
fmt.Println("人员表为空!")
}else{
fmt.Println("人员表不为空!")
}
engine.Sync2(new(CityTable))
cityEmpt,err := engine.IsTableEmpty(new(CityTable))
if err != nil{
panic(err.Error())
}
if cityEmpt{
fmt.Println("城市表为空")
}else {
fmt.Println("城市表不为空")
}
var city CityTable
c,_:=engine.Where("city_name=?","上海").Get(&city)
if c{
fmt.Println("数据已经存在",city)
}else {
fmt.Println("数据不存在")
doc0 := CityTable{"上海",120.21,30.12}
i0,_ :=engine.InsertOne(doc0)
fmt.Println("新增结果为",i0)
}
var per PersonTable
b,_:=engine.Where("preson_name = ?","海燕").Get(&per)
if b{
fmt.Println("数据已经存在",per)
}else {
fmt.Println("数据不存在")
doc1:=PresonTable{0,"海燕",18,0}
i1,_ :=engine.InsertOne(doc1)
fmt.Println("新增结果",i1)
}
}
type PersonTable struct {
Id int64 `xorm:"pk autoincr"`
PersonName string `xorm:"varchar(24)"`
PersonAge int `xrom:"int default 0"`
PersonSex int `xrom:"notnull"`
}
type CityTable struct {
CityName string
CityLongitude float32
CityLatitude float32
}