mysql 第三方包
import _ "github.com/go-sql-driver/mysql"func openProcDB(username, password, addr, name string) *sql.DB {//root:password@/name?parseTime=True&loc=Local&charset=utf8//修改为://root:password@/name?parseTime=True&loc=Local&charset=utf8mb4&collation=utf8mb4_unicode_ciconnStr := fmt.Sprintf(`%s:%s@tcp(%s)/%s?charset=utf8mb4&collation=utf8mb4_unicode_ci&parseTime=%t&loc=%s&timeout=%s&readTimeout=%s`,username,password,addr,name,true,url.QueryEscape("Asia/Shanghai"),"5s", // 连接超时设置"10s", // 读取超时设置)db, err := sql.Open("mysql", connStr)if err != nil {log.Fatalf(err, "数据库连接失败:%s", name)}// 设置连接池db.SetConnMaxLifetime(4 * time.Hour)db.SetMaxOpenConns(200)db.SetMaxIdleConns(100)err = db.Ping()if err != nil {log.Fatalf(err, "数据库连接失败ping:%s", name)}return db
}
注意readTimeout 如果你的sql 比较慢最好不要设置否则出现错误:: invalid connection解决 去除readTimeout,或者设置大一点
mysql 查询时间
show global variables like 'net_read_timeout'