在一个循环中使用go func进行数据库插入操作。

huangapple go评论68阅读模式
英文:

go func for db insert operation inside a for loop

问题

我是你的中文翻译助手,以下是翻译好的内容:

我对golang还不熟悉。我已经了解了go协程(go routines),但我想知道它是否可以用于数据库插入操作。我有以下场景:

  1. 需要为不同类型的产品插入行。

例如:如果我有5个产品,我需要将其id、名称和创建时间插入为行。所以总共有5行对应5个产品。以下的方法是否适合使用:

for _, j := range items {
   go func(j product_object){
     obj := prepare_dto(j)
     save_in_db(obj)
}(j)
}

我进行了试验,分别使用了带有和不带有go func的方法:

  1. 不使用go func的平均时间复杂度为22毫秒。

  2. 使用go func的平均时间复杂度为427纳秒。

上述方法是否是数据库操作的良好实践?

英文:

I am new to golang. I have read about go routines. But I am wondering whether it can be used in db insert operations. I have the following scenario

  1. Need to insert rows for different types of products in each row.

Eg: If I have 5 products I need to insert its id, name, created_at as rows.So total 5 rows for 5 products.Is the following approach good to use

for _, j := range items {
   go func(j product_object){
     obj := prepare_dto(j)
     save_in_db(obj)

}(j)
}

I made a trial with and without using go func

  1. Without using go func avg time complexity is 22ms

  2. With using go func avg time complexity is 427ns

Is the above approach a good practise for db operation?

答案1

得分: 1

是的,你可以这样做。然而,你正在对数据库进行len(items)次调用,这可能会因为连接过多而导致数据库负荷过大。在for循环中插入/更新数据库几乎总是一个不好的主意。我建议你使用批量插入,只需一次调用数据库即可。

英文:

Yes, you can do it. However, you are making len(items) calls to the database, which could potentially wear down your database due to too many connections. It's almost always a bad idea to insert / update to the database within a for loop. I suggest you to do a batch insert with only one call to the database.

huangapple
  • 本文由 发表于 2023年1月19日 13:11:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75167985.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定