Closed fi0 closed 6 years ago
The Go documentation for the SQL library has very good information on how to handle database connections. I've included a couple of links to some documentation you might find useful. I've been using that package extensively for projects and would be glad to help with any questions about its usage. Thanks!
You can have persistent database connection by storing the connection in a global variable as long as the lambda container runs. It will then establish a new connection if it starts from a cold state. This way you'd not have to open and close a connection on each request to the lambda, which is quite expensive and slow.
I don't think there is any way to close the connection when the lambda container stops.
import "database/sql"
var db *sql.DB
func NewConnection(connection string) (*sql.DB, error) {
// Check if a connection is already open
if db != nil {
return db, nil
}
return sql.Open("postgres", connection)
}
You can have persistent database connection by storing the connection in a global variable as long as the lambda container runs. It will then establish a new connection if it starts from a cold state. This way you'd not have to open and close a connection on each request to the lambda, which is quite expensive and slow.
I don't think there is any way to close the connection when the lambda container stops.
import "database/sql" var db *sql.DB func NewConnection(connection string) (*sql.DB, error) { // Check if a connection is already open if db != nil { return db, nil } return sql.Open("postgres", connection) }
What am I missing here? that global var is never initialised in this snippet so it would always return nil and thus instantiate a new connection??
@julienbonastre I think you're right that something is amiss. You need to create the new connection if it is nil
- this is stored in the global var db
and is available on future executions.
Mine is working like this:
var db *sql.DB
func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
if db == nil {
db = GetDatabaseConnection()
}
...
}
func main() {
lambda.Start(HandleRequest)
}
What's the recommended way to open and close a database connection?