Home > Backend Development > Golang > How to connect golang to mysql

How to connect golang to mysql

Release: 2020-03-27 15:56:28
Original
3774 people have browsed it

How to connect golang to mysql

mysql database go driver installation

The driver for golang to connect to the database user is: go-sql-driver

Installation method: Open the command line and execute go command:

go get -u github.com/go-sql-driver/mysql
Copy after login

mysql database connection:

Build the connection, the format is: "Username: Password @tcp (IP: Port)/database?charset=utf8 "

Open the database, the former is the driver name, so you need to import: _ "github.com/go-sql-driver/mysql"

Set the maximum number of database connections and set the maximum idle database Number of connections

Implementation code:

//数据库配置
const (
    userName = "root"
    password = "123456"
    ip = "127.0.0.1"
    port = "3306"
    dbName = "loginserver"
)
//Db数据库连接池
var DB *sql.DB

//注意方法名大写,就是public
func InitDB()  {
    //构建连接:"用户名:密码@tcp(IP:端口)/数据库?charset=utf8"
    path := strings.Join([]string{userName, ":", password, "@tcp(",ip, ":", port, ")/", dbName, "?charset=utf8"}, "")

    //打开数据库,前者是驱动名,所以要导入: _ "github.com/go-sql-driver/mysql"
    DB, _ = sql.Open("mysql", path)
    //设置数据库最大连接数
    DB.SetConnMaxLifetime(100)
    //设置上数据库最大闲置连接数
    DB.SetMaxIdleConns(10)
    //验证连接
    if err := DB.Ping(); err != nil{
        fmt.Println("opon database fail")
        return
    }
    fmt.Println("connnect success")
}
Copy after login

For more golang knowledge, please pay attention to the golang tutorial column on the PHP Chinese website.

The above is the detailed content of How to connect golang to mysql. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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