当预期返回多行的查询未返回任何行时,返回一个错误。

huangapple go评论73阅读模式
英文:

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")
    }

huangapple
  • 本文由 发表于 2021年12月24日 04:08:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/70466934.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定