英文:
Return an error when no rows are returned by a query that is expected to return multiple rows
问题
我有下面的代码片段,目的是从我们所有的仓库中获取客户的忠诚积分。有可能客户有一个id,但没有注册忠诚积分。
使用该客户的id将导致查询返回零行,这不是一个错误。
我希望在这种情况下返回一个错误,以便稍后处理。
我正在寻找最佳的解决方法。
我对编程和golang都很陌生,还不太熟悉。
query := `select coalesce(lc.total_points, 0),
w.machine_name from
lcustomerpoints lc
join warehouses w
on lc.machine_ip = w.machine_ip
where lc.loyaltycard_number = $1;`
rows, err := l.DB.Query(query, user_id)
if err != nil {
return nil, err
}
defer rows.Close()
loyaltyPoints := []*LoyaltyPoint{}
for rows.Next() {
l := LoyaltyPoint{}
err := rows.Scan(&l.Points, &l.Outlet)
if err != nil {
return nil, err
}
loyaltyPoints = append(loyaltyPoints, &l)
}
if err = rows.Err(); err != nil {
return nil, err
}
英文:
I have the code snippet below, the idea is to get the loyalty points of a customer from all our warehouses. There is a possibility that a customer will have an id but is not registered for loyalty.
Using that customer's id will cause the query below to return zero rows, which is not an error.
I would like to return an error when that happens so that I can handle it later.
I am looking for the best possible way to do this.
I am new to programming and golang, I don't really know my way around just yet.
query := `select coalesce(lc.total_points, 0),
w.machine_name from
lcustomerpoints lc
join warehouses w
on lc.machine_ip = w.machine_ip
where lc.loyaltycard_number = $1;`
rows, err := l.DB.Query(query, user_id)
if err != nil {
return nil, err
}
defer rows.Close()
loyaltyPoints := []*LoyaltyPoint{}
for rows.Next() {
l := LoyaltyPoint{}
err := rows.Scan(&l.Points, &l.Outlet)
if err != nil {
return nil, err
}
loyaltyPoints = append(loyaltyPoints, &l)
}
if err = rows.Err(); err != nil {
return nil, err
}
答案1
得分: 1
计算for
循环迭代的次数:
count := 0
for rows.Next() {
count++
...
}
if count == 0 {
return fmt.Errorf("从查询中获取到0行")
}
英文:
Count the number of times the for
loop iterates:
count := 0
for rows.Next() {
count++
...
}
if count == 0 {
return fmt.Errorf("Got 0 rows from query")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论