dtvjl64442 2015-01-25 10:55
浏览 110
已采纳

Golang,mysql:错误1040:连接过多

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?

  • 写回答

3条回答 默认 最新

  • doumaji6215 2015-01-25 11:43
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度