英文:
Go, pgx: SELECT query returns only one row
问题
Golang,pgx:
我正在尝试从t_example表中获取所有行(目前有20个项目),但是由于某种原因只返回一个(第一个)。我尝试进行调试,发现在第一次迭代后,rows.Next()返回false。
你能帮我提供一些建议吗?
我是个新手,但我已经提前在这里寻找了类似的情况
我的代码:
func (ts *exampleStorage) GetAll() *[]Example {
q := `SELECT id, name FROM t_example`
rows := ts.client.Query(context.Background(), q)
example := make([]Example, 0)
for rows.Next() {
var ex Example
rows.Scan(&ex.Id, &ex.Name)
example = append(example, ex)
}
return &example
}
英文:
Golang, pgx:
I am trying to get all rows from t_example (currently 20 items), however for some reason only one returns (the first one). I tried to debug and rows.Next() returns false after the first iteration.
Could you please help me with advice?
I'm a newbie, but I've tried to find similar cases here in advance
My code:
func (ts *exampleStorage) GetAll() *[]Example {
q := `SELECT id, name FROM t_example`
rows := ts.client.Query(context.Background(), q)
example := make([]Example, 0)
for rows.Next() {
var ex Example
rows.Scan(&ex.Id, &ex.Name)
example = append(example, ex)
}
return &example
}
答案1
得分: 2
你的代码没有检查错误:
row.Scan(&ex.Id, &ex.Name)
可能会返回一个错误(在pgx
实现中,这个错误对于rows
迭代是致命的):
err := rows.Scan(&ex.Id, &ex.Name)
if err != nil {
fmt.Printf("*** rows.Scan error: %s", err)
return nil, err
}
- 在
sql.Rows / pgx.Rows
的错误检查中有一个陷阱:你应该在退出for rows.Next() {
循环之后检查是否发生了错误:
for rows.Next() {
...
}
// 在最后一个 rows.Next() 之后检查 rows.Err():
if err := rows.Err(); err != nil {
// 除了在 'rows.Scan()' 调用中触发的错误之外,
// 还可能发生一些不好的情况,比如由于网络错误导致的响应截断等等...
fmt.Printf("*** iteration error: %s", err)
return nil, err
}
return example, nil
一个附注:在绝大多数情况下,你不应该返回一个切片的指针(例如:*[]Example
),而是返回一个切片(例如:[]Example
)。
英文:
Your code doesn't check for errors :
row.Scan(&ex.Id, &ex.Name)
could return an error (and, inpgx
implementation, this error is fatal for therows
iteration) :
err := rows.Scan(&ex.Id, &ex.Name)
if err != nil {
fmt.Printf("*** rows.Scan error: %s", err)
return nil, err
}
- there is a gotcha with
sql.Rows / pgx.Rows
error checking : you should check if an error occurred after exiting thefor rows.Next() {
loop :
for rows.Next() {
...
}
// check rows.Err() after the last rows.Next() :
if err := rows.Err(); err != nil {
// on top of errors triggered by bad conditions on the 'rows.Scan()' call,
// there could also be some bad things like a truncated response because
// of some network error, etc ...
fmt.Printf("*** iteration error: %s", err)
return nil, err
}
return example, nil
a side note : in the vast majority of cases you don't want to return a pointer to a slice (e.g: *[]Example
) but a slice (e.g: []Example
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论