The following column will introduce you to the Golang global sql database connection from the golang tutorial column. I hope it will be helpful to friends in need!
Golang How to write the sql database connection as global, without the need for frequent creation and destruction every time, reducing database consumption and code complexity.
The database connection is usually defined in db.go under the model layer (the name is customized, it can also be database or sql, related to the database)
Because I am using mongoDb here, it is model /mgo.go
package model import ( "context" _ "fmt" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "log" "time" ) type mgo struct { uri string //数据库网络地址 database string //要连接的数据库 //collection string //要连接的集合 } var ( DB *mongo.Database ) func Connect() (*mongo.Database, error) { var m = &mgo{ "mongodb://localhost:27017", "数据库名", //"数据库表名", } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() client, err := mongo.Connect(ctx, options.Client().ApplyURI(m.uri)) if err != nil { log.Print(err) } DB = client.Database(m.database) return DB, err }
Then initialize in main.go
func main() { //初始化mongodb model.Connect() }
When you need to perform database operations, call directly in the model DB can be
collection := model.DB.Collection("表名") //插入操作 insertResult, err := collection.InsertOne(context.TODO(), "内容")
mysql or other database or gorm framework, the same is true.
For more related technical articles, please visit the go language tutorial column!
The above is the detailed content of About Golang global sql database connection. For more information, please follow other related articles on the PHP Chinese website!