duanlei0282 2019-02-18 17:06
浏览 8
已采纳

按参考或按值扫描功能

I have the following code:

statement := `SELECT id from source where mgmt = $1 `
var exists string
errUnique := dr.db.QueryRow(statement, mgmt).Scan(exists)
if errUnique != nil && errUnique != sql.ErrNoRows {
    return errUnique
}

The above code works for me. However, shouldn't my .Scan(&exists) have a by reference? This does not work. On the other hand, when I change exists to a bool as seen here var exists bool the .Scan(&exists) suddenly works. Why isn't the string exists and .Scan(&exists) not working?

  • 写回答

1条回答 默认 最新

  • dongpan2788 2019-02-18 18:23
    关注

    You should have exists be the same type as, or a compatible type to, the type of the value you are retrieving from the database.

    Since you're selecting the id column, I will assume that it is an integer, and therefore you should declare exists as follows var exists int. If, however, you want to find out whether a row is present in the table or not you would generally use a query of the form:

    SELECT EXISTS(SELECT 1 FROM source WHERE mgmt= $1)
    

    (at least in postgres, I'm not sure what db you're using)

    EXISTS:

    The argument of EXISTS is an arbitrary SELECT statement, or subquery. The subquery is evaluated to determine whether it returns any rows. If it returns at least one row, the result of EXISTS is “true”; if the subquery returns no rows, the result of EXISTS is “false”.

    Then your Go code would something like this:

    query := `SELECT EXISTS(SELECT 1 FROM source WHERE mgmt = $1)`
    
    var exists bool
    if err := dr.db.QueryRow(query, mgmt).Scan(&exists); err != nil {
        return err
    }
    
    if exists {
        // already taken
    } else {
        // unique
    }
    

    Also note that since EXISTS always returns a boolean value you don't have to check the error against sql.ErrNoRows, if you do get an error it would not be that one.

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

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)