gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:35:38 29 4
gpt4 key购买 nike

我有以下代码:

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com