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
}