标签:lse golang delete multi ping 数据 ORC localhost ast
beego 框架是优秀得go REST API开发框架。下面针对beego中各类数据库连接操作做一个总结。
beego中的orm操作支持三种数据库:mysql,sqlite3,postgersql。三种数据库的驱动如下:
import (
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
)
对于以上三类数据库的使用,最好使用orm进行操作,因为简单的增删查改已经实现了通用的接口封装。无需再根据每一个模型,单独的实现一套增删查改。另外,orm也支持原生sql查询,复杂的sql操作可以直接使用orm.Raw()进行原生查询,简单快捷。
// 参数1 driverName
// 参数2 数据库类型
// 这个用来设置 driverName 对应的数据库类型
// mysql / sqlite3 / postgres 这三种是默认已经注册过的,所以可以无需设置
orm.RegisterDriver("mysql", orm.DRMySQL)
ORM 必须注册一个别名为 default 的数据库,作为默认使用。
ORM 使用 golang 自己的连接池
// 参数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)
orm.RegisterModel(new(User), new(Profile), new(Post))
自此,就可以愉快的使用orm提供的接口进行数据库操作了。
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
}
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...)
}
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...)
}
golang orm可以连接postgres,但是好像不支持数据库中的schema.
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)
}
使用非orm连接方式,除了mysql,sqlite3,postgresql外,其他的如sqlserver,mongodb,redis等等,都有自己的连接方式。
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
}
import (
"database/sql"
_ "github.com/mattn/go-sqlite3"
)
func GetDBConn() (*sql.DB, error) {
return sql.Open("sqlite3", "./data/location.db")
}
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
}
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)
}
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)
}
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
}
标签:lse golang delete multi ping 数据 ORC localhost ast
原文地址:https://www.cnblogs.com/tianwenxue/p/10083509.html