package dbquery import ( "database/sql" "log" "errors" "strings" "time" "git.tetele.net/tgo/helper" _ "github.com/go-sql-driver/mysql" ) var DB *sql.DB func Connect(DBHOST, DBUSER, DBPWD, DBNAME, DBPORT string, conns ...int) error { log.Println("database connectting...") var dbConnErr error if DBHOST != "" && DBUSER != "" && DBPWD != "" && DBPORT != "" { //&& DBNAME != "" for i := 0; i < 10; i++ { time.Sleep(time.Second * 5) DB, dbConnErr = sql.Open("mysql", DBUSER+":"+DBPWD+"@tcp("+DBHOST+":"+DBPORT+")/"+DBNAME+"?charset=utf8") if dbConnErr != nil { log.Println("ERROR", "can not connect to Database, ", dbConnErr) } else { if len(conns) > 0 { DB.SetMaxOpenConns(conns[0]) //用于设置最大打开的连接数,默认值为0表示不限制 } else { DB.SetMaxOpenConns(200) //默认值为0表示不限制 } if len(conns) > 1 { DB.SetMaxIdleConns(conns[1]) //用于设置闲置的连接数 } else { DB.SetMaxIdleConns(50) } DB.Ping() log.Println("database connected") DB.SetConnMaxLifetime(time.Minute * 2) break } } } else { return errors.New("db connection params errors") } return dbConnErr } func CloseConn() error { return DB.Close() } /** * 检测表名 */ func getTableName(dbName, table string) string { if strings.Contains(table, ".") { return table } if dbName != "" { return helper.StringJoin(dbName, ".", table) } else { return table } } func GetDbTableName(dbName, table string) string { return getTableName(dbName, table) } func judg() []string { return []string{"=", ">", "<", "!=", "<=", ">="} }