Hello,
I am working on a Golang http based project for last 6 months and I am looking for the best way to connect to DB using a persistant connection.
The reason for checking for efficient method is I am getting “too many files open” error and it is crashing the system.
Could anyone please help me by providing your feedback if the code for DB is efficient or not:
//Variable stores DBConn and will be called in any function
var DbConn *sql.DB
func DbOpenConn() (*sql.DB, error) {
connstr := "conn_string"
DbConn, err := sql.Open("mysql", connstr)
CheckErr(err)
DbConn.SetMaxIdleConns(10)
DbConn.SetMaxOpenConns(50)
return DbConn, err
}
//Check if the conn is still alive
func FixConn() (*sql.DB) {
checkping := DbConn.Ping()
var err error
if checkping != nil { //if error
DbConn, err = DbOpenConn()
CheckErr(err)
return DbConn
}
return DbConn
}
// function to execute the statements
func DbExecute(db *sql.DB, query string, params ...interface{}) (sql.Result, error) {
db = FixConn()
stmt, err := db.Prepare(query)
CheckErr(err)
defer stmt.Close()
res, err := stmt.Exec(params...)
CheckErr(err)
return res, err
}
func DbQueryGetRowsParams(db *sql.DB, query string, params ...interface{}) (*sql.Rows, error) {
db = FixConn()
stmt, err1 := db.Prepare(query)
CheckErr(err1)
defer stmt.Close()
rows, err2 := stmt.Query(params...)
CheckErr(err2)
return rows, err2
}
Now I am calling it as:
func MyFunc(w http.ResponseWriter, r *http.Request) {
db := funcs.DbConn
selDB, err = funcs.DbQueryGetRowsParams(db, query, params)
for selDB.Next() {
//Some code
}
selDB.Close() //using it either with or without defer
}
I think my code is fine but still would like an expert advice if I need to improve something.
Actually, I am literally pulling my hairs due to the “too many files open” error. I am analyzing my code from last two days but still not successful.
Thanks