douji5746 2018-07-31 19:09
浏览 51
已采纳

如何创建一个空的sql.Rows实例?

I have a function that returns (*sql.Rows, error) in Go. Under some circumstances, there's nothing to return, but also no error. The choices seems to be:

if (...) {
    return nil, nil
}

and then, in the caller:

rows, err := fn()
if err != nil {
    return nil, err
}

if rows == nil {
   ...
} else {
    for rows.Next() {
    ...
    }
}

or else returning a special error which I then check for. I think it would be a lot more elegant if I could return a valid Rows instance, but that does nothing but return false when its Next() method is called, like this:

if (...) {
    return EmptyRows(), nil
}

and, in the caller:

rows, err := fn()
if err != nil {
    return nil, err
}

for rows.Next() {
    ...
}

I could do something like:

if (...) {
    return db.QueryRows("select * from something where true=false"), nil
}

but that seems pretty goofy. Any recommendations?

  • 写回答

1条回答 默认 最新

  • doujuchuan9915 2018-07-31 19:38
    关注

    I would handle this a little differently, and just pass in the handler to your function. So if your function is currently:

    func YourFunc() (*sql.Rows, error) {
        // ...
        if (...) {
            return nil, nil
        }
        return rows, nil
    }
    

    It would have it be:

    func yourFunc() (*sql.Rows, error) {
        // ...
        if (...) {
            return nil, sql.ErrNoRows
        }
        return rows, nil
    }
    
    func YourFunc(cb func(*sql.Rows)) error {
        rows, err := yourFunc()
        if err == sql.ErrNoRows {
            return nil
        }
        if err != nil {
            return err
        }
        cb(rows)
        return nil
    }
    

    And then in your caller:

    err := YourFunc(func(row *sql.Rows) {
        for rows.Next() {
            // ...
        }
    })
    

    This will have the function you pass only get called if there are rows, you get the error if it's one you care about, and the caller's syntax is pretty clean.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试