组件分享之后端组件——基于Golang实现的database/sql附加功能组件dbr
背景
近期正在探索前端、后端、系统端各类常用组件与工具,对其一些常见的组件进行再次整理一下,形成标准化组件专题,后续该专题将包含各类语言中的一些常用组件。欢迎大家进行持续关注。
组件基本信息
- 组件:dbr
- 开源协议:MIT license
内容
本节我们分享一个基于Golang实现的database/sql附加功能组件dbr,它可以实现超快速的性能和便利性。
具体使用方式如下:
1、安装与加载
go get -u github.com/gocraft/dbr/v2
import "github.com/gocraft/dbr/v2"
2、打开连接
- // create a connection (e.g. "postgres", "mysql", or "sqlite3")
- conn, _ := Open("postgres", "...", nil)
- conn.SetMaxOpenConns(10)
-
- // create a session for each business unit of execution (e.g. a web request or goworkers job)
- sess := conn.NewSession(nil)
-
- // create a tx from sessions
- sess.Begin()
3、创建和使用
- sess := mysqlSession
- tx, err := sess.Begin()
- if err != nil {
- return
- }
- defer tx.RollbackUnlessCommitted()
-
- // do stuff...
-
- tx.Commit()
4、将数据加载到结构中
- // columns are mapped by tag then by field
- type Suggestion struct {
- ID int64 // id, will be autoloaded by last insert id
- Title NullString `db:"subject"` // subjects are called titles now
- Url string `db:"-"` // ignored
- secret string // ignored
- }
-
- // By default gocraft/dbr converts CamelCase property names to snake_case column_names.
- // You can override this with struct tags, just like with JSON tags.
- // This is especially helpful while migrating from legacy systems.
- var suggestions []Suggestion
- sess := mysqlSession
- sess.Select("*").From("suggestions").Load(&suggestions)
5、带有 where-value 插值的
- // database/sql uses prepared statements, which means each argument
- // in an IN clause needs its own question mark.
- // gocraft/dbr, on the other hand, handles interpolation itself
- // so that you can easily use a single question mark paired with a
- // dynamically sized slice.
-
- sess := mysqlSession
- ids := []int64{1, 2, 3, 4, 5}
- sess.Select("*").From("suggestions").Where("id IN ?", ids)
具体使用方式可以参见该文档
本文声明:
88x31.png
本作品由 cn華少 采用 知识共享署名-非商业性使用 4.0 国际许可协议 进行许可。