golang connect to mysql database

The Go project, that is, the golang code, needs to implement operations such as inserting data into the database, and the following code is required:

1. Find a folder (mine is the db folder) and create the file dbConn.go

package db

import (
        "database/sql"

        _ " xxx /mysql"   //(The mysql folder here is downloaded to my project from github.com/go-sql-driver/mysql)  

         "xxx/g"

        "log"
        "sync"
)


var (
        dbLock    sync.RWMutex
        dbConnMap map[string]*sql.DB
)

var DB *sql.DB


//Initialize the database connection, here the initDB() method will be called in the main.go file of the project

func InitDB() {
        var err error
        DB, err = makeDbConn()
        if DB == nil || err != nil {
                log.Fatalln("g.InitDB, get db conn fail", err)
        }

        dbConnMap = make(map[string]*sql.DB)
        log.Println("g.InitDB ok")
}


//When you need to interact with the database, call this GetDbConn method to get a database link

func GetDbConn(connName string) (c *sql.DB, e error) {
        dbLock.Lock()
        defer dbLock.Unlock()

        var err error

  var dbConn *sql.DB
        dbConn = dbConnMap[connName]
        if dbConn == nil {
                dbConn, err = makeDbConn()
                if dbConn == nil || err != nil {
                        closeDbConn(dbConn)
                        return nil, err
                }
                dbConnMap[connName] = dbConn
        }

        err = dbConn.Ping()
        if err != nil {
                closeDbConn(dbConn)
                delete(dbConnMap, connName)
                return nil, err
        }

        return dbConn, err
}

//执行数据库连接的具体代码
func makeDbConn() (conn *sql.DB, err error) {
        conn, err = sql.Open("mysql", g.Config().xxx.Database ) //The g.Config().xxx.Database here, fill in according to your own actual configuration, such as mine here The Database of the xxx field in the cfg.json file is the connection information of the actual database: root:@tcp(127.0.0.1:3306)/graph?loc=Local&parseTime=true
        if err != nil {
                return nil, err
        }

        conn.SetMaxIdleConns (g.Config().DbInfo.MaxIdle)
        err = conn.Ping()

        return conn, err

}

func closeDbConn(conn *sql.DB) {
        if conn != nil {
                conn.Close()
        }

}


2. In the main() method of the main.go file of the project, add the initial database call

package main

import (
        "xxx/db"   //(where xxx is the path of the code in the first step)
)

func main() {

           //Initialize the database

          db.InitDB()

}


3. When the code needs to add, delete, modify and check the database, such as the reporter.go file in my cron package, the database needs to be called

package cron


//This method needs to update the data in the database

func reportAgentStatus(interval time.Duration) {

                                         dbConn, err := db.GetDbConn("hostTable") //The hostTable here is filled in casually, that is, you give yourself a name for this database connection
                                          if err != nil {
                                                 log.Println("[ERROR] get dbConn fail")
                                           }

                                          sql := ""
                                          sql = fmt.Sprintf(
                                               "insert into host(hostname, ip, community) values ​​('%s', '%s', '%s') on duplicate key update ip ='%s', community='%s'",
                                               val.ReportRequest.Hostname,
                                               val.ReportRequest.IP,
                                               val.ReportRequest.Community,
                                               val.ReportRequest.IP,
                                               val.ReportRequest.Community,

                                           )

                                          _, err2 := dbConn.Exec(sql)
                                          if err2 != nil {
                                          log.Println("err exec failure")

}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324587867&siteId=291194637