使用xorm工具,根据数据库自动生成 go 代码

使用xorm工具,根据数据库自动生成 go 代码

参考自 https://www.cnblogs.com/artong0416/p/7456674.html

1、首先我们要下载该工具 :

go get github.com/go-xorm/cmd/xorm

2、同时需要安装对应的 driver :

需要哪个就安装哪个,不需要全装

go get github.com/go-sql-driver/mysql  //MyMysql
go get github.com/ziutek/mymysql/godrv  //MyMysql
go get github.com/lib/pq  //Postgres
go get github.com/mattn/go-sqlite3  //SQLite

3、需要下载 xorm :

go get github.com/go-xorm/xorm

可以编译 cmd/xorm 会生成 xorm 工具, 加入环境变量。
也可以 cd $GOPATH/src/github.com/go-xorm/cmd/xorm

这时候,执行 xorm help reverse 能获取帮助信息如下:

usage: xorm reverse [-s] driverName datasourceName tmplPath [generatedPath] [tableFilterReg]

according database's tables and columns to generate codes for Go, C++ and etc.

    -s                Generated one go file for every table
    driverName        Database driver name, now supported four: mysql mymysql sqlite3 postgres
    datasourceName    Database connection uri, for detail infomation please visit driver's project page
    tmplPath          Template dir for generated. the default templates dir has provide 1 template
    generatedPath     This parameter is optional, if blank, the default value is model, then will
                      generated all codes in model dir
    tableFilterReg    Table name filter regexp

可以知道,执行参数 -s 表示为每张表创建一个单独文件。接下来的参数依次是:驱动,数据源,模板目录(在源码的 /cmd/xorm/templates/goxorm 可根据需求定制),生成目录,表格过滤条件。

接下来我们以 Mysql 为例介绍使用方法。

xorm reverse mysql name:password@(ip:port)/xxx?charset=utf8 $GOPATH/src/github.com/go-xorm/cmd/xorm/templates/goxorm

这里输出目录参数省略,会在当前目录建立一个 model 目录,该目录下就是自动生成的 go 代码, 驼峰命名方式。

name为数据库账号,password为密码,xxx为连接哪个数据库

在模板文件夹下: $GOPATH/src/github.com/go-xorm/cmd/xorm/templates/goxorm
有个config文件里面 genJson=1 代表生成的结构体tag里会有json,0则是没有

你可能感兴趣的:(golang)