I am using a variable "db *sql.DB"
on which I have defined 2 methods A()
and B()
. B()
is called inside A()
with same "db"
variable used to call A()
. (--CHECK CODE--) Now the db.ExecContext()
func is creating a new DB connection in B()
even though the same variable is passed into B()
. It should have used same connection made in its call in A()
. Please tell a solution..
type caller struct{
db *sql.DB
}
func (caller) A(){
db.ExecContext()
db.B()
}
func (caller) B(){
db.ExecContext()
}
So what was happening is I was doing
A(){
rows, _ := db.ExecContext()
defer rows.close()
for rows.Next(){
B()
}
}
So this B() was called before the defer could close that previous connection made by "ExecContext" and started making new connections. I had to call B() in a separate loop after all the rows are fetched.