按参考或按值扫描功能 [英] Scan function by reference or by value

查看:54
本文介绍了按参考或按值扫描功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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
}

上面的代码对我有用.但是,我的 .Scan(& exists)不应该有按引用吗?这是行不通的.另一方面,当我更改为bool时(如此处所示), var存在bool .Scan(& exists)突然起作用.为什么字符串 exists .Scan(& exists)不起作用?

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?

推荐答案

您应该让 exists 与要从其中检索的值的类型相同或兼容.数据库.

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.

由于您选择的是 id 列,因此我假定它是一个 integer ,因此您应声明存在以下内容 var exist int .但是,如果要查找表中是否存在行,通常使用以下形式的查询:

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)

(至少在postgres中,我不确定您使用的是什么数据库)

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

EXISTS :

EXISTS的参数是任意的SELECT语句或子查询.评估子查询以确定它是否返回任何行.如果它返回至少一行,EXISTS的结果为"true";如果子查询不返回任何行,EXISTS的结果为"false".

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".

然后您的Go代码将如下所示:

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
}

还请注意,由于 EXISTS 始终返回布尔值,因此您不必针对 sql.ErrNoRows 检查错误,如果确实收到错误,则不会就是那个.

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.

这篇关于按参考或按值扫描功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆