Home  >  Article  >  Backend Development  >  How to connect to database in golang

How to connect to database in golang

angryTom
angryTomOriginal
2020-03-14 18:17:365528browse

How to connect to database in golang

How to connect to the database in golang

1. To connect to the database, you first need to have a connection driver and install the driver

go get github.com/go-sql-driver/mysql

After successful download, it will be saved to the src subdirectory under the GOPATH directory of the current system

(Free learning video tutorial recommended: mysql video tutorial)

2. Connect to the database

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

● Open the database , the former is the driver name, so it needs to be imported:

“github.com/go-sql-driver/mysql”

● Set the maximum number of database connections and set the maximum number of idle connections in the database

● Verify the connection: use the Ping() function

3. Golang database connection sample code:

import (
	"database/sql"
	"fmt"
	"strings"

	// 安装方式: go get -u github.com/go-sql-driver/mysql
	_ "github.com/go-sql-driver/mysql"
)

var (
	dbhostsip  = "127.0.0.1:3306"
	dbusername = "root"
	dbpassword = "123456"
	dbname     = "chat"
)

// 初始化数据库
func InitDB() (*sql.DB, error) {
	//构建连接信息
	dbinfo := strings.Join([]string{dbusername, ":", dbpassword, "@tcp(", dbhostsip, ")/", dbname, "?charset=utf8"}, "")
	fmt.Println(dbinfo)
	//打开数据库,前面是驱动名称,所以要导入:mysql驱动github.com/go-sql-driver/mysql
	dbins, err := sql.Open("mysql", dbinfo)
	if nil != err {
		fmt.Println("Open Database Error:", err)
		return nil, err
	}
	// 设置数据库的最大连接数
	dbins.SetConnMaxLifetime(100)
	// 设置数据库最大的闲置连接数
	dbins.SetMaxIdleConns(10)
	// 验证连接
	if err = dbins.Ping(); nil != err {
		fmt.Println("Open Database Fail,Error:", err)
		return nil, err
	}
	fmt.Println("Connect Success!!!")
	return dbins, nil
}

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 to database in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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