Skip to content

Error 1040: Too many connections #268

@codeisallaround

Description

@codeisallaround

I open the database connection once, and reuse it for all spawned goroutines (see code below).
Why do I get the "too many connection" error, as I opened only one connection?

(I read #112 and #111 , but I think I have a different issue.)

ApacheBench:

ab -k -c 3000 -n 3000 -k http://localhost:8080/test/entry

Code:

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql" // tested it with master and v. 1.2
    "log"
    "net/http"
    "time"
)

func main() {
    db, err := sql.Open("mysql", "root:@/test") 
    if err != nil {
        log.Fatal(err)
    }
    //db.SetMaxIdleConns(10000)
    defer db.Close()

    err = db.Ping()
    if err != nil {
        log.Fatal("DB not ready")
    }

    http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
        wwwHandler(w, req, db)
    })

    // accepts new connections in an infinite loop and 
    // spawns new goroutines to handle them:
    http.ListenAndServe(":8080", nil)
}

func wwwHandler(w http.ResponseWriter, r *http.Request, db *sql.DB) {
    fmt.Fprintf(w, "%s: Hi there '%s'!", time.Now().Format(time.RFC3339), r.URL.Path[1:])
    gopher(db)
}

func gopher(db *sql.DB) {
    var sStmt string = "INSERT INTO data (name, acc_id, value) VALUES (?, 2, ?);"

    stmt, err := db.Prepare(sStmt)
    if err != nil {
        log.Fatal(err)
    }

    res, err := stmt.Exec(time.Now(), 1)
    if err != nil || res == nil {
        log.Fatal(err)
    }

    stmt.Close()
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions