go - 按引用或按值扫描函数

标签 go

我有以下代码:

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) 不应该有一个引用吗?这是行不通的。另一方面,当我将 exists 更改为 bool 时 var exists bool .Scan(&exists) 突然起作用了。为什么字符串 exists.Scan(&exists) 不起作用?

最佳答案

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

由于您选择的是 id 列,我假设它是一个 integer,因此您应该声明 exists 如下 var exists int。但是,如果您想了解表中是否存在某行,您通常会使用以下形式的查询:

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

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

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

然后你的 Go 代码会是这样的:

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 总是返回一个 bool 值,因此您不必根据 sql.ErrNoRows 检查错误,如果您收到错误,它不会成为那个。

关于go - 按引用或按值扫描函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54752167/

相关文章:

go - 如何在 Go 中创建不固定长度的 slice

go - 获取和设置任意 slice 的长度

mongodb - Golang MongoDB 导入问题

arrays - 将目录读取为 []byte 而不压缩它

go - 将 go 应用程序部署到 Bluemix 后服务器无法启动

go - 如何在函数中使用接口(interface),其中参数是另一个具有相同函数列表的接口(interface)?

MongoDB BulkWrite 内存成本

go - go中通过方法发送到 channel 的值,无法在外部接收

postgresql - 执行: "sqlboiler": executable file not found in $PATH

go - 有人可以解释这个使用 channel 的 Go 代码块吗?我不明白它是如何一次执行 500 个 Action 的