From d9e7d4249f5b7d876f2ca4531f9540196148bd41 Mon Sep 17 00:00:00 2001 From: hailaz <739476267@qq.com> Date: Wed, 11 Sep 2019 16:48:00 +0800 Subject: [PATCH] improve dbBase.doBatchInsert() --- database/gdb/gdb_base.go | 23 ++++------------------- 1 file changed, 4 insertions(+), 19 deletions(-) diff --git a/database/gdb/gdb_base.go b/database/gdb/gdb_base.go index 18d1019ce..30f32c6c4 100644 --- a/database/gdb/gdb_base.go +++ b/database/gdb/gdb_base.go @@ -484,15 +484,16 @@ func (bs *dbBase) doBatchInsert(link dbLink, table string, list interface{}, opt } // 构造批量写入数据格式(注意map的遍历是无序的) batchNum := gDEFAULT_BATCH_NUM - if len(batch) > 0 { + if len(batch) > 0 && batch[0] > 0 { batchNum = batch[0] } - for i := 0; i < len(listMap); i++ { + listMapLen := len(listMap) + for i := 0; i < listMapLen; i++ { for _, k := range keys { params = append(params, convertParam(listMap[i][k])) } values = append(values, valueHolderStr) - if len(values) == batchNum { + if len(values) == batchNum || (i == listMapLen-1 && len(values) > 0) { r, err := bs.db.doExec(link, fmt.Sprintf("%s INTO %s(%s) VALUES%s %s", operation, table, keyStr, strings.Join(values, ","), updateStr), @@ -510,22 +511,6 @@ func (bs *dbBase) doBatchInsert(link dbLink, table string, list interface{}, opt values = values[:0] } } - // 处理最后不构成指定批量的数据 - if len(values) > 0 { - r, err := bs.db.doExec(link, fmt.Sprintf("%s INTO %s(%s) VALUES%s %s", - operation, table, keyStr, strings.Join(values, ","), - updateStr), - params...) - if err != nil { - return r, err - } - if n, err := r.RowsAffected(); err != nil { - return r, err - } else { - batchResult.lastResult = r - batchResult.rowsAffected += n - } - } return batchResult, nil }