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 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动