gorose使用示例

it2022-07-06  170

package main import ( "fmt" "github.com/gohouse/gorose" //import Gorose _ "github.com/go-sql-driver/mysql" //只执行github.com/go-sql-driver/mysql的init函数 "errors" "strconv" ) func main() { //mysql数据库配置 var DbConfig = map[string]interface{}{ // Default database configuration "Default": "mysql_dev", // (Connection pool) Max open connections, default value 0 means unlimit. "SetMaxOpenConns": 0, // (Connection pool) Max idle connections, default value is 1. "SetMaxIdleConns": 10, // Define the database configuration character "mysql_dev". "Connections": map[string]map[string]string{ "mysql_dev": {// 定义名为 mysql_dev 的数据库配置 "host": "192.168.2.179", // 数据库地址 "username": "a", // 数据库用户名 "password": "b@", // 数据库密码 "port": "3306", // 端口 "database": "a", // 链接的数据库名字 "charset": "utf8", // 字符集 "protocol": "tcp", // 链接协议 "prefix": "", // 表前缀 "driver": "mysql", // 数据库驱动(mysql,sqlite,postgres,oracle,mssql) }, }, } db, err := gorose.Open(DbConfig) if err != nil { panic(err.Error()) } defer db.Close() //延迟关闭 // 简单查询 res, err := db.Query("select * from users;") fmt.Println(res) // 条件查询 res, err = db.Query("select * from users where userid=?",1) fmt.Println(res) //简单链式查询 fmt.Println(db.Table("users").First()) //带条件的链式查询 fmt.Println(db.Table("users").Fields("userid as id ,username as name").Where("userid", "=", 3).Get()) //带别名的查询 res, err := db.Table("users").Fields("userid as ID,username as Name").Get() // 查询结果转成json res,err = db.Table("users").Fields("userid as id ,username as name").Where("userid", "=", 3).Get() jsonStr := db.JsonEncode(res) fmt.Println(jsonStr) //开启事务,参数是一个匿名函数 db.Transaction(func() error { // 链式插入数据 res1 ,err1 := db.Table("version").Data(map[string]interface{}{"MainVersion":1,"SubVersion":2}).Insert(true) if err1 != nil { return err1 } if res1 == 0 { return errors.New("Insert failed") } //链式 更新数据 res1,err1 = db.Table("scene").Data(map[string]interface{}{"modelname":"model003"}).Where("id",10).Update() if err1 != nil { return err1 } if res1 == 0 { return errors.New("Update failed") } return nil }) // 事务结束 }

转载于:https://www.cnblogs.com/qianlicao/p/8520561.html

相关资源:Go-gorose(goorm)一个小巧强悍的go语言数据库操作orm

最新回复(0)