1 回答
TA贡献1796条经验 获得超7个赞
您编写的代码存在一些问题。避免连接泄漏问题的直接答案是关闭迭代rows
器,如文档中所述。调用它的正常方法是在defer
声明中:
rows, err := db.Query(
"select 1 from things where id = $1",
thing,
)
if err != nil {
return nil, fmt.Errorf("can't select thing (%d): %w", thing, err)
}
defer rows.Close()
found := false
for rows.Next() {
found = true
break
}
其次,由于您关心的只是单个结果,因此根本没有理由获取多行结果集,这也将隐式解决连接泄漏问题。如果我们在这里进行调整:
row, err := db.QueryRow(
"select EXISTS(SELECT 1 from things where id = $1)",
thing,
)
if err != nil {
return nil, fmt.Errorf("can't select thing (%d): %w", thing, err)
}
var found bool
if err := row.Scan(&found); err != nil {
return nil, fmt.Errorf("Failed to scan result: %w", err)
}
- 1 回答
- 0 关注
- 105 浏览
添加回答
举报