Use *DB.Raw(sql string, values ...interface{}) method directly occur Error 1040: Too many connections

gorm v1.25.1 dsn := "root:xxx@tcp(127.0.0.1:3306)/xxx?charset=utf8mb4&parseTime=True&loc=Local" gormDb, err := gorm.Open(gormMySQL.Open(dsn)) writeConn := gormDb.WriteDB _, err := writeConn.Raw("sql clause").Rows when I execute writeConn.Raw("sql clause").Rows multiple times, then I will occur Error 1040: Too many connections , but If I change to below, then this error is disappear:

dsn := "root:xxx@tcp(127.0.0.1:3306)/xxx?charset=utf8mb4&parseTime=True&loc=Local" gormDb, err := gorm.Open(gormMySQL.Open(dsn)) writeConn := gormDb.WriteDB tx := db.Begin() defer func() { tx.Commit() }() _, err := tx.Raw("sql clause").Rows I want to know why use writeConn.Raw("sql clause").Rows directly cause this error? does it open a new connection to mysql db and how can I close this single connection ?

The document you expected this should be explained

Expected answer

Comment From: ivila

@yuanybin When you call Rows method, you will get a *sql.Rows value, don't eat it with underscore, cause you have to call its Close method manually, you can check the sql.Rows Type, it's in official package. change your codes to the following and it should work:

    rows, err := writeConn.Raw("sql clause").Rows()
    if (err != nil) {
        return err
    }
    defer rows.Close()

And if you just care about the err, do not care about the return value of your database, just change your codes to the following:

    // you don't have to call the Rows method.
    err := writeConn.Raw("sql clause").Err

And last, please see the design of golang official package database/sql, you have to understand the design of Connection Pool and the Close method(when calling the Close method, the connection will be returned to the Connection Pool, or drop it if it exceed MaxIdle)

Comment From: yuanybin

thanks