首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用ants golang调用数据库插入操作

如何使用ants golang调用数据库插入操作
EN

Stack Overflow用户
提问于 2021-11-09 16:34:27
回答 1查看 24关注 0票数 0

我有一个for循环,它将数据插入到两个不同的表中。在这种情况下,我如何使用ants(下面的包)。

GH包编号:https://github.com/panjf2000/ants

代码语言:javascript
复制
for _, row := range rows {
 user := User{}
 user.Name = row.Name
 user.Email = row.Email
 err := dm.Insert(&user)
 if err != nil {
  panic(err)
 }
 address := Address{}
 address.Address1 = row.Address1
 address.Address2 = row.Address2
 address.PinCode = row.PinCode
 address.City = row.City
 err := dm.Insert(&address)
 if err != nil {
  panic(err)
 }
}
EN

回答 1

Stack Overflow用户

发布于 2021-11-09 21:54:24

类似于:

代码语言:javascript
复制
func insertRow() {
    // TODO add code to get 'rows'

    const workerCount = 10
    p, err := NewPool(workerCount)
    if err != nil {
        panic(err)
    }

    defer p.Release()

    rowChan := make(chan RowType)

    var wg sync.WaitGroup

    insertRecords := func() {
        defer wg.Done()
   
        row <- rowChan

        user := User{}
        user.Name = row.Name
        user.Email = row.Email
        err := dm.Insert(&user)
        if err != nil {
            panic(err)
        }
        
        address := Address{}
        address.Address1 = row.Address1
        address.Address2 = row.Address2
        address.PinCode = row.PinCode
        address.City = row.City
        err := dm.Insert(&address)
        if err != nil {
            panic(err)
        }
    }

    for _, row := range rows {
        wg.Add(1)
        _ = ants.Submit(insertRecords)
        rowChan <- row
    }

    wg.Wait()
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69901786

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档