当前位置: 首页 > 工具软件 > Gfast > 使用案例 >

gfast原生sql实现数据插入和更新以及使用事务

蔡辰钊
2023-12-01
"github.com/gogf/gf/frame/g"

type Sum struct {
	C int `orm:"column:C"`
}
sum := new(Sum)
_ = g.DB().Raw("SELECT COUNT(*) as C FROM e_topic WHERE deleted_at IS NULL").Scan(sum)
fmt.Println(sum)
student := dao.SysStudentAddReq{
	StudentName: "娃哈哈",
}
_, err = g.DB().Exec("insert into sys_student(student_name) values(?)", student.StudentName)
if err != nil {
	g.Log().Error(err)
	return
}
g.DB().Transaction(req.Ctx, func(ctx context.Context, tx *gdb.TX) error {
	student := dao.SysStudentAddReq{
		StudentName: "旺仔牛奶",
	}
	res, err := tx.Exec("insert into sys_student(student_name) values(?)", student.StudentName)
	if err != nil {
		return err
	}
	id, err := res.LastInsertId()
	err = errors.New("插入失败")
	if err != nil {
		return err
	}
	_, err = tx.Exec(`update sys_student set student_name = ? where student_id = ?`, "爽歪歪", id)
	if err != nil {
		return err
	}
	return nil
})
 类似资料: