Go,pgx:SELECT 查询只返回一行

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

}


白衣染霜花
浏览 187回答 1
1回答

UYOU

您的代码不检查错误: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() {    ...}// 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旁注:在绝大多数情况下,您不想返回指向切片(例如:)的指针,而是返回切片(例如*[]Example:)[]Example
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go