tyltr技术窝

在go module下,对mysql数据库,使用xorm:

1.安装xorm ,xorm命令工具,mysql驱动#

1
2
3
go  get github.com/go-sql-driver/mysql
go get github.com/go-xorm/xorm
go get github.com/go-xorm/cmd/xorm

2. 在项目目录下执行#

1
go build -tags mysql

3.在项目目录下,创建templates/goxorm目录以及配置#

在templates/goxorm创建config、struct.go.tpl文件

3.1 templates/goxorm/config#

1
2
3
lang=go
genJson=1
prefix=

3.2 templates/goxorm/struct.go.tpl#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package {{.Models}}

{{$ilen := len .Imports}}
{{if gt $ilen 0}}
import (
{{range .Imports}}"{{.}}"{{end}}
)
{{end}}

{{range .Tables}}
type {{Mapper .Name}} struct {
{{$table := .}}
{{range .ColumnsSeq}}{{$col := $table.GetColumn .}} {{Mapper $col.Name}} {{Type $col}} {{Tag $table $col}}
{{end}}
}

{{end}}

4.创建models目录#

执行 xorm reverse 生成的model文件,都在models目录中

5.执行命令#

命令:
xorm reverse mysql <username>:<password>@tcp(<host>:<port>)/<database>?charset=utf8 templates/goxorm

  • username 数据库用户名
  • password 数据库密码
  • host 数据库host
  • port 端口
  • database 数据库
1
xorm  reverse  mysql  root:@tcp(127.0.0.1:3306)/shop?charset=utf8  templates/goxorm

  • 如果出现错误no matches found: root:@tcp(127.0.0.1:3306)/shop?charset=utf8
    解决方案:将mysql 链接中的()和?转义,正确链接为
    xorm reverse mysql root:@tcp\(127.0.0.1:3306\)/shop\?charset=utf8 templates/goxorm