drbvm26000 2019-02-13 18:14
浏览 9

如何进行数据库查询,然后检查结果

I need to check if my query returns true or false. If it returns false, I want it to error out. Here is my code:

func (dr *dbrepo) checkIfUnique(datacenterstring) error {
    statement := `select exists(select 1 from source where datacenter = $3)`

    _, checkIfExists := dr.db.Query(statement)
    if checkIfExists != nil {
        log.Print("Error  is not unique", checkIfExists)
        return checkIfExists
    }
    return nil
}

The problem is: I think I need to convert checkIfExists from a row to a bool and then see if it is true or false. But I am not sure on how to do that. Any ideas? Is there a better way to do this?

  • 写回答

1条回答 默认 最新

  • dongzj2015 2019-02-13 18:38
    关注

    Query() does not return true or false. It returns two values: *Rows & error.

    func (db *DB) Query(query string, args ...interface{}) (*Rows, error) {
        ...
    }
    

    In your case: checkIfExists is the error. With this error, you can already tell of the query succeeded or failed. Like you do it:

    if checkIfExists != nil {
        return checkIfExists
    }
    

    If you want more information (such as the rows retrieved by your query), then you will need to replace the _ with a variable. Let's call it rows and then you use rows.Scan() to copy the data in the columns to your destinations. See database/sql docs for more information.

    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法