去,PGX:选择查询仅返回一行
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码未检查错误:
row.scan(& ex.id,ex.name)
可能会返回错误(并且,在pgx
instructation in offormant,此错误对于行
迭代是致命的):sql.Rows/pgx.Rows
错误检查的陷阱:您应该检查是否发生错误 退出for Rows.next(){
loop:旁注:在绝大多数情况下,您不想将指针返回到一个切片(例如:
*[]示例
),但是切片(例如:[]示例
)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) :sql.Rows / pgx.Rows
error checking : you should check if an error occurred after exiting thefor rows.Next() {
loop :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
)