postgresql - Golang-Postgres ..Closing database connection not working for particular query -


i using golang access postgresql. function

for {     db, err := database.getnewconnection(dbname)      err = db.queryrow("select coalesce(count(1),0) table").scan(&count)      if count == 0 {          var insert = "insert table(last_update_time,next_update_time,schedule_frequency)" +             "values($1,$2,$3)"         prep_ins, err := db.prepare(insert)         if err != nil {             return         }         _, err = prep_ins.exec(cur_time, 1464718530, 86400)         if err != nil {             return         }         defer prep_ins.close()         defer db.close()     } else {         var sel_str = "select next_update_time table"         prep_update, err := db.prepare(sel_str)         if err != nil {              return         }         _, err = prep_update.exec()         if err != nil {             defer prep_update.close()             return         }         defer prep_update.close()         defer db.close()     }     time.sleep(10 * 60 * time.second) } 

every 10 mins , function run , execute statement. working fine connection in idle state. checking using pg_stat_activity, state idle only. every 10 mins, new connection created , went idle state.so keep on increasing. don't know why happening.

thanks in advance.

the for loop infinite loop , never return. means defers never executed , connections won't closed. need add explicit db.close() @ end of loop.

also move initialization of db out of loop if don't need new connection every time perform task. can create single connection , reuse it. if this, move defer statement below initialization of db. if database operations return errors defers close connection.

db, err := database.getnewconnection(dbname) if err != nil {     return fmt.errorf("error in creating database connection: %+v", err) } defer db.close() {      // ...      db.close() } 

by doing ensure connection gets closed on every return path put of function (https://blog.golang.org/defer-panic-and-recover)

if still leave db initialization in loop, remove defers since they'll add defer stack while db connection closed explicitly.


Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -