您可以通过调用SetMaxOpenConns 在您的sql.DB上。




I'm using the github.com/go-sql-driver/mysql driver for go.

I open a database:

db, err := sql.Open("mysql", str)

Then I have two functions that are called 200 times each with following mysql code:

rows, err := db.Query("select name from beehives")
if err != nil {
    panic(err)
}       
defer rows.Close()

The second:

    err = db.QueryRow("select id, secret, shortname from beehives where shortname = ?", beehive).Scan(&id, &secre
    switch {
    case err == sql.ErrNoRows:
        err = errors.New("Beehive '"+beehive+"' not found.")
    case err != nil:
        panic("loginBeehive: "+ err.Error())
    default:
        // ... do the work

The first one is panicing.

How can there be more than one connection when I open the database only once and how do I close them?

A sql.DB maintains a pool of connections to your database. Each time you query your database your program will try to get a connection from this pool or create a new one otherwise. These connections are than put back into the pool once you close them.

rows.Close()db.QueryRow("...")Scan(...)

The basic problem is that you're creating too many queries, of which each one needs a connection, but you are not closing your connections fast enough. This way your program has to create a new connection for each query.

You can limit the maximum number of connections your program uses by calling SetMaxOpenConns on your sql.DB.

这篇关于Golang,mysql:错误1040:连接太多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!