golang 连接MySQL数据库

package connectdata

import (
	"database/sql"
	"fmt"
	"os"

	_ "github.com/go-sql-driver/mysql"
)

func ConnectData() *sql.DB {
	db, err := sql.Open("mysql", "username:123456@(127.0.0.1:3306)/?charset=utf8mb4&parseTime=True&loc=Local")
	if err != nil {
		fmt.Println(err)
	}
	db.SetConnMaxLifetime(100)
	db.SetMaxIdleConns(10)
	if err := db.Ping(); err != nil {
		fmt.Println("open database fail", err)
		os.Exit(1)
	}
	return db
}

  

posted @ 2022-03-30 11:55  昌慶  阅读(170)  评论(0编辑  收藏  举报