Various database connection methods in beego
The beego framework is an excellent go REST API development framework. Below is a summary of various database connection operations in beego.
Orm connection method
Orm operations in beego support three types of databases: mysql, sqlite3, postgersql. The drivers of the three types of databases are as follows:
import ( _ "/go-sql-driver/mysql" _ "/lib/pq" _ "/mattn/go-sqlite3" )
For the use of the above three types of databases, it is best to use orm for operation, because simple additions, deletions, and revisions have implemented general interface encapsulation. There is no need to implement a set of additions, deletions, searches and modifications based on each model. In addition, orm also supports native SQL queries. Complex SQL operations can be used directly to perform native queries using () which is simple and fast.
1.1 Orm usage
a. Register the database driver
// Parameter 1 driverName// Parameter 2 Database type// This is used to set the database type corresponding to driverName// mysql/sqlite3/postgres are registered by default, so you can do without setting it("mysql", )
b. Register a database
ORM must register a database with alias default as default.
ORM uses golang's own connection pool
// Parameter 1 The alias of the database, used to switch database usage in ORM// Parameter 2 driverName// Parameter 3 corresponding link string("default", "mysql", "root:root@/orm_test?charset=utf8") // Parameter 4 (optional) Set maximum idle connection// Parameter 5 (optional) Set the maximum database connection (go >= 1.2)maxIdle := 30 maxConn := 30 ("default", "mysql", "root:root@/orm_test?charset=utf8", maxIdle, maxConn)
c. Register the model
(new(User), new(Profile), new(Post))
From then on, you can happily use the interface provided by orm to perform database operations.
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 Operation example
a. orm connection to mysql
import ( "/astaxie/beego/orm" _ "/go-sql-driver/mysql" ) func init() { ("mysql", ) ("default", "mysql", "root:root@tcp(192.168.1.1:3306)/ming?charset=utf8") (new(User)) ("default", 10) ("default", 100) } func Create(param interface{}) (int64, error) { return ().Insert(param) } func Update(param interface{}, fields ...string) (int64, error) { return ().Update(param, fields...) } func Delete(param interface{}, cols ...string) (int64, error) { return ().Delete(param, cols...) } func Read(md interface{}, cols ...string) error { return ().Read(md, cols...) }
b. Orm connection sqlite3
import ( "/astaxie/beego/orm" _ "/mattn/go-sqlite3" ) func init() { ("sqlite3", ) ("default", "sqlite3", "conf/sqlite_test.db") ("default", 50) ("default", 200) //Set the database time zone // = (new(User)) } func Create(param interface{}) (int64, error) { return ().Insert(param) } func Update(param interface{}, fields ...string) (int64, error) { return ().Update(param, fields...) } func Delete(param interface{}, cols ...string) (int64, error) { return ().Delete(param, cols...) } func Read(md interface{}, cols ...string) error { return ().Read(md, cols...) }
c. orm connection postgresql
golang orm can connect to postgres, but it seems that schema in the database does not support it.
import ( "/astaxie/beego/orm" _ "/lib/pq" ) func init() { ("postgres", ) ("default", "postgres", "host=192.168.1.1 port=5432 user=root password=root dbname=test sslmode=disable") //("schema_name", new(PmPark)) (new(PmPark)) ("default", 10) ("default", 50) }
1.3 Non-orm connection method
Using non-orm connection methods, in addition to mysql, sqlite3, postgresql, other such as sqlserver, mongodb, redis, etc. have their own connection methods.
a. mysql
import ( "fmt" "database/sql" _ "/go-sql-driver/mysql" ) func getMysqlDB() (*, error) { connectString := "root:123456@tcp(localhost:3306)/test?charset=utf8" db, err := ("mysql", connectString) if err != nil { return nil, err } return db, nil }
b. sqlite3
import ( "database/sql" _ "/mattn/go-sqlite3" ) func GetDBConn() (*, error) { return ("sqlite3", "./data/") }
c. postgresql
import ( "database/sql" "errors" "fmt" "time" "/astaxie/beego" _ "/lib/pq" ) var ( host string = "" port int user string = "" password string = "" dbname string = "" max_conn int = 40 idle_conn int = 10 postgreConn * //Global SQL connection, connection pool has been implemented, so you can only create one instance DB_CONN_ERROR error ) func init() { host = ("postgres_host") port, _ = ("postgres_port") user = ("postgres_user") password = ("postgres_password") dbname = ("postgres_dbname") max_conn = ("postgres_max_conn", 50) idle_conn = ("postgres_idle_conn", 10) DB_CONN_ERROR = ("Database connection failed") } func GetPostgresSession() * { if postgreConn == nil { psqlInfo := (`host=%s port=%d user=%s password=%s dbname=%s sslmode=disable`, host, port, user, password, dbname) db, err := ("postgres", psqlInfo) if err != nil { return nil } (30 * ) (max_conn) (idle_conn) // err = () // if err != nil { // return nil // } postgreConn = db } return postgreConn }
d. mongodb
import ( "errors" "time" "/astaxie/beego" "/mgo.v2" ) // Connect to mongodb databasevar ( MongodbAddr string = "" //mongodb database address MongodbName string = "" //mongodb data name MongodbUser string = "" //mongodb username MongodbPasswd string = "" //mongodb password) var ( mongosession * ) func init() { MongodbAddr = ("mongodb_addr") MongodbName = ("mongodb_name") MongodbUser = ("mongodb_username") MongodbPasswd = ("mongodb_passwd") } func GetMongoSession() * { if mongosession == nil { var err error if MongodbUser == "" || MongodbPasswd == "" { mongosession, err = (MongodbAddr) } else { dialInfo := &{ Addrs: string{MongodbAddr}, Direct: false, Timeout: * 30, Database: MongodbName, Source: "admin", Username: MongodbUser, Password: MongodbPasswd, PoolLimit: 4096, // } mongosession, err = (dialInfo) } if err != nil { return nil } } return () } func WithMongoCollection(collectionName string, s func(*) error) error { session := GetMongoSession() if session == nil { return ("Failed to get mongodb connection") } defer () c := (MongodbName).C(collectionName) return s(c) }
import ( "database/sql" "time" "fmt" "/astaxie/beego" _ "/denisenkom/go-mssqldb" ) const ( CONN_LIVE_TIME = 24 //Connection usage time hours) var ( db * = nil //Global database connection) func init() { host := ("yr_host") port, err := ("yr_port") if err != nil { port = 1433 } user := ("user") password := ("password") dbName := ("name") connString := ("server=%s;port%d;database=%s;user id=%s;password=%s", host, port, dbName, user, password) db, err = ("mssql", connString) if err != nil { return } (200) (50) ((CONN_LIVE_TIME) * ) }
import ( "time" "/astaxie/beego" "/gomodule/redigo/redis" ) var ( db_addr string = "" db_password string = "" redisPool * //Redis connection pool) func init() { db_addr = ("redis_addr") db_password = ("redis_password") } //Get Redis connection poolfunc newRedisPool(server, password string) (*, error) { var err error return &{ MaxIdle: 32, IdleTimeout: 180 * , Dial: func() (, error) { var c c, err = ("tcp", server) if err != nil { return nil, err } if password != "" { if _, err = ("AUTH", password); err != nil { () return nil, err } } return c, err }, TestOnBorrow: func(c , t ) error { _, err := ("PING") return err }, }, err } /* Get the redis database connection */ func GetRedisConnection() (, error) { if redisPool == nil { var err error redisPool, err = newRedisPool(db_addr, db_password) if err != nil { return nil, err } } return (), nil }
The above is the detailed content of detailed examples of various database connection methods for ORM operations in Beego. For more information about Beego ORM database connection, please pay attention to my other related articles!