sqlx: batch insert operation

func BatchAdd(ctx context.Context, listData []*DataTab) (int64, error) {
	operation := "batch_add_shipment_group_audit_log"
	sqlStatement := fmt.Sprintf("INSERT INTO %s (%s) VALUES ", TableName, ColumnNames)
	var values []interface{}
	for  _, row := range listData {
		sqlStatement += "(?,?,?,?,?),"
		values = append(values, row.field1, row.field2, row.field3)
	}
	result, err := db.Exec(operation, strings.TrimSuffix(sqlStatement, ","), values...)
	if err != nil {
		logCtx.Withs("operation", operation).WithError(err).Error("failed to BatchAdd")
		return 0, err
	}
	lastInsertId, err := result.LastInsertId()
	if err != nil {
		return 0, err
	}
	return lastInsertId, nil
}
上一篇:sqlx库使用


下一篇:sqlx 查询一对多数据,并赋值给结构体