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
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") }
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!