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 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?