A
A
alst1612016-10-16 12:59:35
PostgreSQL
alst161, 2016-10-16 12:59:35

Why are new database connections created?

Faced the following problem.

rows, err := db.Query("SELECT id,type,name FROM auto WHERE status=1")
checkErr(err)
defer rows.Close()
for rows.Next() {
      var id, type, id_type int
      var name string
      rows.Scan(&id, &type, &name)
      db.QueryRow("SELECT id FROM type WHERE id=$1",type).Scan(&id_type)
      .........
}

and so at the first access to basis one connection is created, and at execution of the second request new connection is formed. why?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2016-10-16
@pav5000

Until rows.Close() is executed, the query to the database is not completed, the connection hangs and pulls data from the database as rows.Next() is executed.
If you do not want to create new connections, you can optimize this program by making the database give you the data you need in one request. Using a selection from several tables, JOINs or nested queries at worst.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question