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.

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

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据