Golang,mysql:错误1040:连接太多 [英] Golang, mysql: Error 1040: Too many connections

查看:1595
本文介绍了Golang,mysql:错误1040:连接太多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用github.com/go-sql-driver/mysql驱动程序进行操作。



我打开一个数据库:

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

然后我有两个函数被调用200次,每个函数都有以下的mysql代码:

 行,err:= db.Query(从蜂箱中选择名字)
if err!= nil {
panic(err)
}
推迟rows.Close()

第二种:

  err = db.QueryRow(选择ID,秘密,来自beehives的短名称,其中shortname =?,蜂巢).Scan(& id,&secre)
switch {
case err == sql.ErrNoRows:
err = errors.New(Beehive'+ beehive +'not found。)
case err!= nil:
panic(loginBeehive: + err.Error())
默认值:
// ...完成工作

第一个是恐慌。



怎么可能有多个连接当我打开数据库只有一次,如何关闭它们?

sql.Open并没有真正打开到你的数据库的连接。



一个sql.DB维护与您的数据库的连接池。每次查询数据库时,程序都会尝试从该池中获取连接,否则将创建一个新连接。这些连接在关闭它们后会放回池中。



这就是 rows.Close()确实。
当您调用 Scan(...)时,您的 db.QueryRow(...) code $。

基本问题是你创建了太多的查询,每个查询都需要一个连接,但是你没有快速关闭你的连接足够。通过这种方式,您的程序必须为每个查询创建一个新的连接。



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



请参阅 http://go-database-sql.org/surprises.html 以获取更多信息。


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?

解决方案

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆