脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Golang - Beego中ORM操作各类数据库连接方式详细示例

Beego中ORM操作各类数据库连接方式详细示例

2022-09-23 10:39Jeff的技术栈 Golang

这篇文章主要为大家介绍了Beego中ORM操作各类数据库连接方式详细示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步早日升职加薪

beego中各类数据库连接方式

beego 框架是优秀得go REST API开发框架。下面针对beego中各类数据库连接操作做一个总结。

orm连接方式

beego中的orm操作支持三种数据库:mysql,sqlite3,postgersql。三种数据库的驱动如下:

?
1
2
3
4
5
import (
    _ "github.com/go-sql-driver/mysql"
    _ "github.com/lib/pq"
    _ "github.com/mattn/go-sqlite3"
)

对于以上三类数据库的使用,最好使用orm进行操作,因为简单的增删查改已经实现了通用的接口封装。无需再根据每一个模型,单独的实现一套增删查改。另外,orm也支持原生sql查询,复杂的sql操作可以直接使用orm.Raw()进行原生查询,简单快捷。

1.1 orm使用方式

a. 注册数据库驱动程序

?
1
2
3
4
5
// 参数1   driverName
// 参数2   数据库类型
// 这个用来设置 driverName 对应的数据库类型
// mysql / sqlite3 / postgres 这三种是默认已经注册过的,所以可以无需设置
orm.RegisterDriver("mysql", orm.DRMySQL)

b.注册数据库

ORM 必须注册一个别名为 default 的数据库,作为默认使用。
ORM 使用 golang 自己的连接池

?
1
2
3
4
5
6
7
8
9
// 参数1        数据库的别名,用来在 ORM 中切换数据库使用
// 参数2        driverName
// 参数3        对应的链接字符串
orm.RegisterDataBase("default", "mysql", "root:root@/orm_test?charset=utf8")
// 参数4(可选)  设置最大空闲连接
// 参数5(可选)  设置最大数据库连接 (go >= 1.2)
maxIdle := 30
maxConn := 30
orm.RegisterDataBase("default", "mysql", "root:root@/orm_test?charset=utf8", maxIdle, maxConn)

c. 注册模型

?
1
orm.RegisterModel(new(User), new(Profile), new(Post))

自此,就可以愉快的使用orm提供的接口进行数据库操作了。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
type Ormer interface {
    Read(interface{}, …string) error
    ReadOrCreate(interface{}, string, …string) (bool, int64, error)
    Insert(interface{}) (int64, error)
    InsertMulti(int, interface{}) (int64, error)
    Update(interface{}, …string) (int64, error)
    Delete(interface{}) (int64, error)
    LoadRelated(interface{}, string, …interface{}) (int64, error)
    QueryM2M(interface{}, string) QueryM2Mer
    QueryTable(interface{}) QuerySeter
    Using(string) error
    Begin() error
    Commit() error
    Rollback() error
    Raw(string, …interface{}) RawSeter
    Driver() Driver
}

1.2 操作示例

a. orm连接mysql

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import (
    "github.com/astaxie/beego/orm"
    _ "github.com/go-sql-driver/mysql"
)
func init() {
    orm.RegisterDriver("mysql", orm.DRMySQL)
    orm.RegisterDataBase("default", "mysql", "root:root@tcp(192.168.1.1:3306)/ming?charset=utf8")
    orm.RegisterModel(new(User))
 
    orm.SetMaxIdleConns("default", 10)
    orm.SetMaxOpenConns("default", 100)
}
func Create(param interface{}) (int64, error) {
    return orm.NewOrm().Insert(param)
}
func Update(param interface{}, fields ...string) (int64, error) {
    return orm.NewOrm().Update(param, fields...)
}
func Delete(param interface{}, cols ...string) (int64, error) {
    return orm.NewOrm().Delete(param, cols...)
}
func Read(md interface{}, cols ...string) error {
    return orm.NewOrm().Read(md, cols...)
}

b. orm连接sqlite3

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import (
    "github.com/astaxie/beego/orm"
    _ "github.com/mattn/go-sqlite3"
)
func init() {
    orm.RegisterDriver("sqlite3", orm.DRSqlite)
    orm.RegisterDataBase("default", "sqlite3", "conf/sqlite_test.db")
    orm.SetMaxIdleConns("default", 50)
    orm.SetMaxOpenConns("default", 200)
    //设置数据库时区
    //orm.DefaultTimeLoc = time.UTC
    orm.RegisterModel(new(User))
}
func Create(param interface{}) (int64, error) {
    return orm.NewOrm().Insert(param)
}
func Update(param interface{}, fields ...string) (int64, error) {
    return orm.NewOrm().Update(param, fields...)
}
func Delete(param interface{}, cols ...string) (int64, error) {
    return orm.NewOrm().Delete(param, cols...)
}
func Read(md interface{}, cols ...string) error {
    return orm.NewOrm().Read(md, cols...)
}

c. orm连接 postgresql

golang orm可以连接postgres,但是好像不支持数据库中的schema.

?
1
2
3
4
5
6
7
8
9
10
11
12
import (
    "github.com/astaxie/beego/orm"
    _ "github.com/lib/pq"
)
func init() {
    orm.RegisterDriver("postgres", orm.DRPostgres)
    orm.RegisterDataBase("default", "postgres", "host=192.168.1.1 port=5432 user=root password=root dbname=test sslmode=disable")
    //orm.RegisterModelWithPrefix("schema_name", new(PmPark))
    orm.RegisterModel(new(PmPark))
    orm.SetMaxIdleConns("default", 10)
    orm.SetMaxOpenConns("default", 50)
}

1.3非orm连接方式

使用非orm连接方式,除了mysql,sqlite3,postgresql外,其他的如sqlserver,mongodb,redis等等,都有自己的连接方式。

a. mysql

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import (
    "fmt"
    "database/sql"
 
    _ "github.com/go-sql-driver/mysql"
)
func getMysqlDB() (*sql.DB, error) {
    connectString := "root:123456@tcp(localhost:3306)/test?charset=utf8"
 
    db, err := sql.Open("mysql", connectString)
    if err != nil {
        return nil, err
    }
 
    return db, nil
}

b. sqlite3

?
1
2
3
4
5
6
7
import (
    "database/sql"
    _ "github.com/mattn/go-sqlite3"
)
func GetDBConn() (*sql.DB, error) {
    return sql.Open("sqlite3", "./data/location.db")
}

c. postgresql

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import (
    "database/sql"
    "errors"
    "fmt"
    "time"
    "github.com/astaxie/beego"
    _ "github.com/lib/pq"
)
var (
    host     string = ""
    port     int
    user     string = ""
    password string = ""
    dbname   string = ""
    max_conn  int = 40
    idle_conn int = 10
    postgreConn *sql.DB //全局sql连接,已实现连接池,所以可以只创建一个实例
    DB_CONN_ERROR error
)
func init() {
    host = beego.AppConfig.String("postgres_host")
    port, _ = beego.AppConfig.Int("postgres_port")
    user = beego.AppConfig.String("postgres_user")
    password = beego.AppConfig.String("postgres_password")
    dbname = beego.AppConfig.String("postgres_dbname")
    max_conn = beego.AppConfig.DefaultInt("postgres_max_conn", 50)
    idle_conn = beego.AppConfig.DefaultInt("postgres_idle_conn", 10)
    DB_CONN_ERROR = errors.New("数据库连接失败")
}
func GetPostgresSession() *sql.DB {
    if postgreConn == nil {
        psqlInfo := fmt.Sprintf(`host=%s port=%d user=%s password=%s dbname=%s sslmode=disable`,
            host, port, user, password, dbname)
        db, err := sql.Open("postgres", psqlInfo)
        if err != nil {
            return nil
        }
        db.SetConnMaxLifetime(30 * time.Minute)
        db.SetMaxOpenConns(max_conn)
        db.SetMaxIdleConns(idle_conn)
        //      err = db.Ping()
        //      if err != nil {
        //          return nil
        //      }
        postgreConn = db
    }
    return postgreConn
}

d. mongodb

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import (
    "errors"
    "time"
    "github.com/astaxie/beego"
    "gopkg.in/mgo.v2"
)
// 连接mongodb数据库
var (
    MongodbAddr   string = "" //mongodb数据库地址
    MongodbName   string = "" //mongodb数据名称
    MongodbUser   string = "" //mongodb用户名
    MongodbPasswd string = "" //mongodb密码
)
var (
    mongosession *mgo.Session
)
func init() {
    MongodbAddr = beego.AppConfig.String("mongodb_addr")
    MongodbName = beego.AppConfig.String("mongodb_name")
    MongodbUser = beego.AppConfig.String("mongodb_username")
    MongodbPasswd = beego.AppConfig.String("mongodb_passwd")
}
func GetMongoSession() *mgo.Session {
    if mongosession == nil {
        var err error
        if MongodbUser == "" || MongodbPasswd == "" {
            mongosession, err = mgo.Dial(MongodbAddr)
        } else {
            dialInfo := &mgo.DialInfo{
                Addrs:     string{MongodbAddr},
                Direct:    false,
                Timeout:   time.Second * 30,
                Database:  MongodbName,
                Source:    "admin",
                Username:  MongodbUser,
                Password:  MongodbPasswd,
                PoolLimit: 4096, // Session.SetPoolLimit
            }
            mongosession, err = mgo.DialWithInfo(dialInfo)
        }
        if err != nil {
            return nil
        }
    }
    return mongosession.Clone()
}
func WithMongoCollection(collectionName string, s func(*mgo.Collection) error) error {
    session := GetMongoSession()
    if session == nil {
        return errors.New("获取mongodb连接失败")
    }
    defer session.Close()
    c := session.DB(MongodbName).C(collectionName)
    return s(c)
}

e.sqlserver

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import (
    "database/sql"
    "time"
    "fmt"
    "github.com/astaxie/beego"
    _ "github.com/denisenkom/go-mssqldb"
)
const (
    CONN_LIVE_TIME = 24 //连接使用时间 小时
)
var (
    db       *sql.DB = nil //全局数据库连接
)
func init() {
    host := beego.AppConfig.String("yr_host")
    port, err := beego.AppConfig.Int("yr_port")
    if err != nil {
        port = 1433
    }
    user := beego.AppConfig.String("user")
    password := beego.AppConfig.String("password")
    dbName := beego.AppConfig.String("name")
    connString := fmt.Sprintf("server=%s;port%d;database=%s;user id=%s;password=%s", host, port, dbName, user, password)
    db, err = sql.Open("mssql", connString)
    if err != nil {
        return
    }
    db.SetMaxOpenConns(200)
    db.SetMaxIdleConns(50)
    db.SetConnMaxLifetime(time.Duration(CONN_LIVE_TIME) * time.Hour)
}

f.redis

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import (
    "time"
    "github.com/astaxie/beego"
    "github.com/gomodule/redigo/redis"
)
var (
    db_addr     string = ""
    db_password string = ""
    redisPool *redis.Pool //redis连接池
)
func init() {
    db_addr = beego.AppConfig.String("redis_addr")
    db_password = beego.AppConfig.String("redis_password")
}
//获取Redis连接池
func newRedisPool(server, password string) (*redis.Pool, error) {
    var err error
    return &redis.Pool{
        MaxIdle:     32,
        IdleTimeout: 180 * time.Second,
        Dial: func() (redis.Conn, error) {
            var c redis.Conn
            c, err = redis.Dial("tcp", server)
            if err != nil {
                return nil, err
            }
            if password != "" {
                if _, err = c.Do("AUTH", password); err != nil {
                    c.Close()
                    return nil, err
                }
            }
            return c, err
        },
        TestOnBorrow: func(c redis.Conn, t time.Time) error {
            _, err := c.Do("PING")
            return err
        },
    }, err
}
/*
获取redis数据库连接
*/
func GetRedisConnection() (redis.Conn, error) {
    if redisPool == nil {
        var err error
        redisPool, err = newRedisPool(db_addr, db_password)
        if err != nil {
            return nil, err
        }
    }
    return redisPool.Get(), nil
}

以上就是Beego中ORM操作各类数据库连接方式详细示例的详细内容,更多关于Beego ORM数据库连接的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/guyouyin123/p/14041582.html

延伸 · 阅读

精彩推荐
  • Golanggolang Gin上传文件返回前端及中间件实现示例

    golang Gin上传文件返回前端及中间件实现示例

    这篇文章主要为大家介绍了golang Gin上传文件返回前端及中间件实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步早日升职加薪...

    Jeff的技术栈6382022-09-19
  • GolangGolang实现对map的并发读写的方法示例

    Golang实现对map的并发读写的方法示例

    这篇文章主要介绍了Golang实现对map的并发读写的方法示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧 ...

    hackssssss5712020-05-23
  • Golanggolang使用grpc+go-kit模拟oauth认证的操作

    golang使用grpc+go-kit模拟oauth认证的操作

    这篇文章主要介绍了golang使用grpc+go-kit模拟oauth认证的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    鹿灏楷silves8182021-05-30
  • Golanggolang flag简单用法

    golang flag简单用法

    本篇文章介绍了golang flag包的一个简单的用法,希望通过一个简单的实例,能让大家了解它的用法,从中获得启发 ...

    大囚长3732020-05-19
  • GolangGolang并发操作中常见的读写锁详析

    Golang并发操作中常见的读写锁详析

    Golang中的锁机制主要包含互斥锁和读写锁互斥锁互斥锁是传统并发程序对共享资源进行控制访问的主要手段,这篇文章主要给大家介绍了关于Golang并发操作中...

    ReganYue11462021-09-17
  • GolangGo使用defer函数要注意的几个点

    Go使用defer函数要注意的几个点

    这篇文章主要介绍了Go使用defer函数要注意的几个点,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下...

    訢亮4542020-06-01
  • GolangGo语言映射内部实现及基础功能实战

    Go语言映射内部实现及基础功能实战

    这篇文章主要为大家介绍了Go语言映射的内部实现和基础功能实战,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪...

    山河已无恙4652022-09-08
  • GolangGo语言中的Struct结构体

    Go语言中的Struct结构体

    这篇文章介绍了Go语言中的Struct结构体,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...

    奋斗的大橙子10592022-07-16