golang mysql大量连接,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?

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值