V
V
Vadim Rublev2021-12-27 00:54:36
go
Vadim Rublev, 2021-12-27 00:54:36

Why, when the connection pool is moved to the file level, does it panic?

This is how the database query works fine:

import (
    _ "github.com/go-sql-driver/mysql"
)

func DBRout() {
    // Пул подключений.
    db, err_DB := sql.Open("mysql", ConnectDB)
      if err_DB != nil {
        fmt.Println("ERROR creating database connection pool:", err_DB)
    }
    defer db.Close()
  
        db_ss.SetMaxOpenConns(25)
        db_ss.SetMaxIdleConns(2)
        db_ss.SetConnMaxLifetime(time.Minute)
    
  // Запрос.
  var err_DBQuery = db.QueryRow("SELECT COUNT(*) FROM `TabTab` WHERE `Col_User` = ? AND ColumnID = ?, 3, UName).Scan(&row_search)
      if err_DBQuery != nil {
    fmt.Println("Query error:", err_DBQuery)
          return
      }
}

func main() {
    var mux = http.NewServeMux()
  mux.HandleFunc("/routDB/", DBRout)
  var serv = &http.Server {
      ...параметры...
  }
  log.Fatal(serv.ListenAndServeTLS(TLScert, TLSkey))
}


And when I take out a pool of connections on level of a file - panics.
import (
    _ "github.com/go-sql-driver/mysql"
)

var db *sql.DB

func DBRout() {		
  // Запрос.
  var err_DBQuery = db.QueryRow("SELECT COUNT(*) FROM `TabTab` WHERE `Col_User` = ? AND ColumnID = ?, 3, UName).Scan(&row_search)
      if err_DBQuery != nil {
      fmt.Println("Query error:", err_DBQuery)
        return
    }
}

func main() {
    // Пул подключений.
    db, err_DB := sql.Open("mysql", ConnectDB)
  if err_DB != nil {
      fmt.Println("ERROR creating database connection pool:", err_DB)
  }
  defer db.Close()
  
        db_ss.SetMaxOpenConns(25)
        db_ss.SetMaxIdleConns(2)
        db_ss.SetConnMaxLifetime(time.Minute)

    var mux = http.NewServeMux()
  mux.HandleFunc("/routDB/", DBRout)
  var serv = &http.Server {
      ...параметры...
  }
  log.Fatal(serv.ListenAndServeTLS(TLScert, TLSkey))
}


Outputs to the console:
2021/12/27 04:02:13 http2: panic serving 127.0.0.1:59951: runtime error: invalid memory address or nil pointer dereference
goroutine 136 [running]: ...

Isn't that bullshit?? )

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2021-12-27
@Vadim Rublev

Well, isn't it bullshit?? )

No, because you have two different variables with the same name - db
A very handy rule.

Когда что-то работает не так, как ты ожидаешь, вини в первую очередь себя, компилятор и рантайм на 99.99999% прав, крайне маловероятно, что с опытом меньше пары лет в языке, ты сможешь найти в нём баг.

And in general, never create global variables. In the product code, they are not needed in 100% of cases

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question