About Golang global sql database connection

藏色散人
Release: 2020-12-23 14:58:12
forward
3302 people have browsed it

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!

About Golang global sql database connection

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

Code:

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
}
Copy after login

Then initialize in main.go

func main() {
  //初始化mongodb
  model.Connect()
}
Copy after login

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(), "内容")
Copy after login

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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template