用go xorm來操作mysql
阿新 • • 發佈:2018-12-16
很有用,來看下:
package main import ( "fmt" "github.com/go-xorm/xorm" "github.com/go-xorm/core" _ "github.com/go-sql-driver/mysql" ) // 對應資料庫的tablename必須為student // 執行mysql時,對應的欄位為xxx,yyy,zzz; 也可以省掉,預設的mysql欄位為id,username,address type Student struct { Id int `xorm:"INT(11) 'xxx'"` Username string `xorm:"VARCHAR(64) 'yyy'"` Address string `xorm:"VARCHAR(256) 'zzz'"` } func main() { engine, err := xorm.NewEngine("mysql", "
[email protected]/taoge?charset=utf8") // dbname是taoge if err != nil{ fmt.Println(err) return } // 如下Ping可以不要 // if err := engine.Ping(); err != nil{ // fmt.Println(err) // return // } //engine.ShowSQL(true) // 顯示SQL的執行, 便於除錯分析 engine.SetTableMapper(core.SnakeMapper{}) st1 := new(Student) st1.Username = "taoge" st1.Address = "China" affected, err := engine.Insert(st1) fmt.Println(affected) st2 := new(Student) result,err := engine.Where("xxx=?", 1).Get(st2) fmt.Println(result) fmt.Println(st2.Username) fmt.Println(st2.Address) }
建立資料庫:
CREATE TABLE `student` (
`xxx` int(11) NOT NULL AUTO_INCREMENT,
`yyy` varchar(64) NOT NULL,
`zzz` varchar(256) NOT NULL ,
PRIMARY KEY (`xxx`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
執行結果:
1 true taoge China
不多說。