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