var engine *xorm.Engine
func main() {
var err error
engine, err = xorm.NewEngine("mysql", "root:123456@tcp(127.0.0.1:3306)/myschool?charset=utf8")
if err != nil {
log.Println(err)
}
// 控制台打印出生成的SQL语句
engine.ShowSQL(true)
}
二、操作mysql数据库
查询
建表语句
CREATE TABLE `student` (
`id` varchar(225) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`name` varchar(225) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`age` int(11) NULL DEFAULT NULL,
`gradeid` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
CREATE TABLE `grade` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`gradename` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
struct结构体
student.go
type Student struct {
Id string `orm:"id,primary" json:"id"`
Name string `orm:"name" json:"name"`
Age int `orm:"age" json:"age"`
Gradeid int `orm:"gradeid" json:"gradeid"`
}
grade.go
type Grade struct {
Id int `orm:"id,primary" json:"id"`
Gradename string `orm:"gradename" json:"gradename"`
}
var strings []string
// Table 需要操作的表名称
err := engine.Table("student").Cols("id").Find(&strings)
if err != nil {
log.Println(err)
}
log.Println("查询到的信息:",strings)
4、Join方法
第一个参数为连接类型,当前支持INNER, LEFT OUTER, CROSS中的一个值, 第二个参数为string类型的表名,表对应的结构体指针或者为两个值的[]string,表示表名和别名, 第三个参数为关联键。
每个学生只在一个班级出现,所以对应的结构体应该加上xorm的index标记
type Student struct {
Id string `orm:"id,primary" json:"id"`
Name string `orm:"name" json:"name"`
Age int `orm:"age" json:"age"`
Gradeid int `orm:"gradeid" json:"gradeid" xorm:"index"`
}
type Grade struct {
Id int `orm:"id,primary" json:"id"`
Gradename string `orm:"gradename" json:"gradename"`
}
type Student struct {
Id string `orm:"id,primary" json:"id"`
Name string `orm:"name" json:"name"`
Age int `orm:"age" json:"age"`
Gradeid int `orm:"gradeid" json:"gradeid" xorm:"index"`
CreatedTime time.Time `xorm:"created"`
}