Golang, mysql: Error 1040: Too many connections

前端 未结 5 1663
终归单人心
终归单人心 2021-02-01 17:57

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 fun

5条回答
  •  [愿得一人]
    2021-02-01 18:30

    sql.Open doesn't really open a connection to your database.

    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.

    This is what rows.Close() does. Your db.QueryRow("...") does the same thing internally when you call 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.

    See http://go-database-sql.org/surprises.html for more information.

提交回复
热议问题