dongya767979565 2018-09-15 13:47
浏览 274
已采纳

golang数据库事务:如果单个exec语句失败,则继续

I am writing a Go app which should insert thousands of values from a file into a database. This works fine, as long as all values can be inserted into the database. If one of the queries fails, all queries afterwards fail because of pq: : current transaction is aborted, commands ignored until end of transaction block

I want to insert all elements and if the insert of an element fails, it should be skipped and the other elements should be inserted.

My Code:

func (db *Database) Insert(values []Value) (transerr error) {
    tx, err := db.Begin()
    if transerr != nil {
        return nil, err
    }
    defer func() {
        if err != nil {
            tx.Rollback()
        } else {
            tx.Commit()
        }
    }
    stmt, err := tx.Prepare("INSERT INTO foo VALUES (?)")
    if err != nil {
        return err
    }

    defer stmt.Close()

    for _, value : range values {
        _, err = stmt.Exec(value)
        if err != nil {
            log.Error(err)
        }
    }
    return nil
}

I tried to add a tx.Rollback() in case a stmt.Exec fails - however this results in sql: statement is closed.

  • 写回答

2条回答 默认 最新

  • douaoj0994 2018-09-20 22:14
    关注

    My solution for the problem looks like this:

    • Do not create a single transaction and add all statements into it, instead just run it without creating transactions.
    • As the values are read in, spawn new go routines and let the transaction run parallelized (be careful with connection limits).
    • Without parallelization, the performance dropped about 30% (from 20s for 25k values to 30s - we did not use parallelization before).
    • With parallelization, the performance increased about 4 times (to 5 seconds) - just be careful you stay within the connection ranges
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 is not in the mmseg::model registry。报错,模型注册表找不到自定义模块。
  • ¥15 安装quartus II18.1时弹出此error,怎么解决?
  • ¥15 keil官网下载psn序列号在哪
  • ¥15 想用adb命令做一个通话软件,播放录音
  • ¥30 Pytorch深度学习服务器跑不通问题解决?
  • ¥15 部分客户订单定位有误的问题
  • ¥15 如何在maya程序中利用python编写领子和褶裥的模型的方法
  • ¥15 Bug traq 数据包 大概什么价
  • ¥15 在anaconda上pytorch和paddle paddle下载报错
  • ¥25 自动填写QQ腾讯文档收集表