dream5694 2016-11-10 00:24
浏览 211
已采纳

golang postgres连接过多错误

I am new to Golang/Postgres and I am doing some testing and getting an pq: sorry, too many clients already error . My postgres instance is set to a max of 100 connections and I am getting that error in this code

    for i := 0; i < 10000; i++ {
    profile_id = profile_id+1
    on, err := db.Query("insert into streams (post,profile_id,created_on) values ($1,$2,$3)", post, profile_id, created_on)
    defer on.Close()

    if err != nil {
        fmt.Fprintln(w, "-1")
        log.Fatal(err)
    }
}

I can usually get in about 60 to 70 inserts then I get that error . All the connections are coming from that one sample in for For loop . What can I be doing wrong, here is my full code . As far as I know 1 connection can hold many different queries so I don't know why it is only giving me 60 to 70 inserts then get the error .

func Insert_Stream(w http.ResponseWriter, r *http.Request) {


wg := sync.WaitGroup{}
wg.Add(1)


go func(){
    defer wg.Done()

db, err := sql.Open("postgres", Postgres_Connect)
if err != nil {
    log.Fatal(err)
    println(err)

}
defer db.Close()

r.ParseForm()
post := r.FormValue("post")
profile_id,err := strconv.Atoi(r.FormValue("profile_id"))
created_on := time.Now()
for i := 0; i < 10000; i++ {
    profile_id = profile_id+1
    on, err := db.Query("insert into streams (post,profile_id,created_on) values ($1,$2,$3)", post, profile_id)
    defer on.Close()

    if err != nil {
        fmt.Fprintln(w, "-1")
        log.Fatal(err)
    }
}

fmt.Fprintln(w, "1")

}()
wg.Wait()

}

I am essentially inserting 10,000 records into the database with a different profile ID for testing .

  • 写回答

1条回答 默认 最新

  • dongtang5057 2016-11-11 06:27
    关注

    DO NOT use defer in loop. Because it will execute when function returns.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?