Mysql connection on Rest Server

I learned in another thread that mysql statements can be declared globally and then used within multiple threads without issue. However, I now have a question about the actual db connection itself.

Do I need to connect to the database within each function that gets called in the REST server or can I declare a single DB connection in the init() and then use it throughout the application?

Thanks,

Glenn

You can define one connection

So I did that but get error about db not existing when I call functions using the db connection I created in the init() function I get an error about there being no connection. If I move it into main() it works and if I move it into the function being called it works.

var db *sql.DB

func init() {
  var err error
  if db, err = connectDB( DBConnect ); err != nil {
      fmt.Println( "Can't connect to the database" )
      return
   } else {
      defer db.Close()
   }   
   if queryuser, err = db.Prepare("select UserID, CurrentDB from optUsers where LoginHash = '?'"); err != nil          {
      println(err)
     return
    }   
}

//this function gets called when connection is received and the ping comes back with error
//if I put it in the init but it comes back good if it is in either of the other functions (main or test)
func test() {
if err = db.Ping(); err != nil {
      HandleError( 0, 500, "No Database Connection Exists\n", w, req )
      return
   }

I believe here’s your problem:

else {
  defer db.Close()
} 

As init works for initialization and runs before your main program, this should close the connection before you start using it. What you want is to gracefully handle errors, kill signals or whatever else happens that means you should close the connection in your main function.

1 Like

ah, I completely didn’t think about that. Good catch.

Thanks,

Glenn

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.