xorm根據(jù)數(shù)據(jù)庫生成go model文件的操作
你懂的,手工翻譯表定義到go結(jié)構(gòu)體是很枯燥的。
so,用xorm搞定。
go get github.com/go-xorm/cmd/xorm
安裝以下依賴,用到哪個裝哪個。
驅(qū)動
Mysql: github.com/go-sql-driver/mysql
Postgres: github.com/lib/pq
SQLite: github.com/mattn/go-sqlite3
MSSQL: github.com/denisenkom/go-mssqldb
逆向生成
Reverse 命令可以轉(zhuǎn)換數(shù)據(jù)庫到所有支持的語言的數(shù)據(jù)結(jié)構(gòu),安裝以后可以用 xorm help reverse查看幫助。
例子:
cd $GOPATH/src/github.com/go-xorm/cmd/xorm sqlite: xorm reverse sqite3 test.db templates/goxorm mysql: xorm reverse mysql root:root@/xorm_test?charset=utf8 templates/goxorm mymysql: xorm reverse mymysql xorm_test2/root/ templates/goxorm postgres: xorm reverse postgres "dbname=xorm_test sslmode=disable" templates/goxorm mssql: xorm reverse mssql "server=test;user id=testid;password=testpwd;database=testdb" templates/goxorm
會在./model目錄下生成go的文件
坑
1、一定要在$GOPATH/src/github.com/go-xorm/cmd/xorm目錄下運(yùn)行,因為在這個目錄下有templets,在解析數(shù)據(jù)庫結(jié)構(gòu)的時候有用。如果在別的目錄下運(yùn)行,會導(dǎo)致命令不報錯,但是無法正常生成對應(yīng)的結(jié)構(gòu)文件。有空可以給github.com/go-xorm/cmd/xorm提個bug,加上錯誤提示。
2、執(zhí)行xorm reverse mysql root:root@127.0.0.1:3306/testdb?charset=utf8 templates/goxorm報錯2017/08/16 14:09:18 [Error] reverse.go:176 default addr for network '127.0.0.1:3306' unknown
解決辦法:
xorm reverse mysql root:root@tcp(127.0.0.1:3306)/testdb?charset=utf8 templates/goxorm xorm reverse mysql root:root@tcp(127.0.0.1:3306)/testdb?charset=utf8 templates/goxorm
補(bǔ)充:「golang」xorm工具生成postgres的model
golang中的orm框架,一般使用xorm的xorm工具根據(jù)數(shù)據(jù)庫表自動生成struct文件
xorm reverse postgres "dbname=queimsi sslmode=disable user=postgres password=123456 host=10.0.2.206 port=5432" /data/workspace/go/src/github.com/go-xorm/cmd/xorm/templates/goxorm
然后就會自動在當(dāng)前目錄下生成表的struct文件
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
Golang使用channel實(shí)現(xiàn)數(shù)據(jù)匯總的方法詳解
這篇文章主要為大家詳細(xì)介紹了在并發(fā)編程中數(shù)據(jù)匯總的問題,并探討了在并發(fā)環(huán)境下使用互斥鎖和通道兩種方式來保證數(shù)據(jù)安全性的方法,需要的可以參考一下2023-05-05
go web 預(yù)防跨站腳本的實(shí)現(xiàn)方式
這篇文章主要介紹了go web 預(yù)防跨站腳本的實(shí)現(xiàn)方式,文中給大家介紹XSS最佳的防護(hù)應(yīng)該注意哪些問題,本文通過實(shí)例代碼講解的非常詳細(xì),需要的朋友可以參考下2021-06-06
golang基礎(chǔ)之waitgroup用法以及使用要點(diǎn)
WaitGroup是Golang并發(fā)的兩種方式之一,一個是Channel,另一個是WaitGroup,下面這篇文章主要給大家介紹了關(guān)于golang基礎(chǔ)之waitgroup用法以及使用要點(diǎn)的相關(guān)資料,需要的朋友可以參考下2023-01-01
Golang并發(fā)編程中Context包的使用與并發(fā)控制
Golang的context包提供了在并發(fā)編程中傳遞取消信號、超時控制和元數(shù)據(jù)的功能,本文就來介紹一下Golang并發(fā)編程中Context包的使用與并發(fā)控制,感興趣的可以了解一下2024-11-11
在Golang中實(shí)現(xiàn)RSA算法的加解密操作詳解
RSA 是一種非對稱加密算法,廣泛使用于數(shù)據(jù)的安全傳輸,crypto/rsa 是 Golang 中實(shí)現(xiàn)了 RSA 算法的一個標(biāo)準(zhǔn)庫,提供了生成公私鑰對、加解密數(shù)據(jù)、簽名和驗簽等功能,本文給大家介紹了在Golang中實(shí)現(xiàn)RSA算法的加解密操作,需要的朋友可以參考下2023-12-12

