go 适配 odbc

最后更新于:2022-04-02 02:47:15

[TOC] > [参考:golang连接达梦数据库的一个坑](https://www.cnblogs.com/bartggg/p/13066944.html) ## odbc 是什么 [ODBC](../%E6%95%B0%E6%8D%AE%E5%BA%93/ODBC.md) ## 概述 ### 取消表的引号 xorm.io/core v1.0.1版本已经支持使用 `engine.Dialect().SetQuotePolicy(core.QuotePolicyNone)` ### 自定义数据库类型 默认 odbc 是 mssql ,导致再用结构体获取查询时,会出现 `select top 10 ...` ``` engine, err := xorm.NewEngine("odbc", "Driver={Kingbase ODBC Driver};Server=192.168.0.127;Database=antdbms;Uid=SYSTEM;Pwd=123456;Port=54321") ``` 如果想使用 mysql ``` engine, err := xorm.NewEngine("odbc", "Driver={MYSQL ODBC 8.0 ANSI Driver};Server=192.168.0.127;Database=antdbms;Uid=root;Pwd=www.upsoft01.com;Port=3306") engine.Dialect().URI().DBType=schemas.MYSQL ``` ## windows 如果本地测试环境为 window 则获取的信息可能为 gbk ,需要进行转义 为 utf_8
main.go ``` package main import ( "fmt" _ "github.com/alexbrainman/odbc" // google's odbc driver "github.com/go-xorm/xorm" "xorm.io/core" "github.com/axgle/mahonia" ) type Address struct { Addressid int64 `xorm:"addressid"` Address1 string `xorm:"address1"` Address2 string `xorm:"address2"` City string `xorm:"city"` Postalcode string `xorm:"postalcode"` } // 字符串解码函数,处理中文乱码 func ConvertToString(src string, srcCode string, tagCode string) string { srcCoder := mahonia.NewDecoder(srcCode) srcResult := srcCoder.ConvertString(src) tagCoder := mahonia.NewDecoder(tagCode) _, cdata, _ := tagCoder.Translate([]byte(srcResult), true) result := string(cdata) return result } func main() { engine, err := xorm.NewEngine("odbc", "driver={DM8 ODBC DRIVER};server=127.0.0.1:5236;database=DM;uid=SYSDBA;pwd=password;charset=utf8") if err != nil { fmt.Println("new engine got error:", err) return } engine.ShowSQL(true)//控制台打印出生成的SQL语句; engine.Logger().SetLevel(core.LOG_DEBUG) if err := engine.Ping(); err != nil { fmt.Println("ping got error:", err) return } // 1) sql查询 results, err := engine.Query("select addressid, address1, address2, city, postalcode from person.address limit 5 offset 2") if err != nil { fmt.Println("查询出错:", err) return } for i, e := range results { fmt.Printf("%v\t", i) for k, v := range e { // 达梦数据库中文默认为gbk fmt.Printf("%v=%v\t", k, ConvertToString(string(v), "gbk", "utf-8")) } fmt.Printf("\n") } fmt.Println("*******************************") // 2) 使用struct 映射结果 engine.SetMapper(core.SameMapper{}) var sliceOfAddress []Address err = engine.Table("person.address").Limit(5, 0).Find(&sliceOfAddress) if err != nil { fmt.Println("查询出错:", err) return } for i,e := range sliceOfAddress { e.Address1 = ConvertToString(e.Address1, "gbk", "utf-8") e.Address2 = ConvertToString(e.Address2, "gbk", "utf-8") e.City = ConvertToString(e.City, "gbk", "utf-8") fmt.Printf("%v=%v\n", i, e) } } ```

';