本文主要是介绍go 数据库连接,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package dbConnection
import (
"database/sql"
"fmt"
"strings"
_ "github.com/go-sql-driver/mysql"
)
//数据库配置
const (
userName = "root"
password = "root"
ip = "127.0.0.1"
port = "3306"
dbName = "go"
)
//连接数据库
func Init() (db *sql.DB, errstr error) {
//构建连接:"用户名:密码@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)
//验证连接
if err := db.Ping(); err != nil {
fmt.Println("open database fail")
return db, nil
}
return db, nil
}
这篇关于go 数据库连接的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!