使用Golang和PostgreSQL时,我无法将变量传递到ST_DWithin查询中。

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

Golang with postgres - unable to pass variable into a ST_DWithin query

问题

非常新手Golang,无法解决这个问题。非常感谢任何帮助。

这是我需要帮助的代码。尝试将纬度等传递到下面的查询中,但无法实现。在node.js中寻找与${latitude}等效的内容...

   latitude := r.URL.Query().Get("lat")
   longitude := r.URL.Query().Get("lon")
   radius := r.URL.Query().Get("rad")


   row := db.QueryRow(`SELECT "name", "website", "coordinates", 
   "description", "rating"
    FROM geospots
    WHERE ST_DWithin("coordinates", ST_MakePoint(latitude = $1, 
   longitude = $2)::geography, radius = $3)`, latitude, longitude)


   错误
   andlers/SpotsInArea.go:15:5: latitude declared but not used
   handlers/SpotsInArea.go:16:5: longitude declared but not used
   handlers/SpotsInArea.go:17:5: radius declared but not used
英文:

Very new to Golang and unable to resolve this. Any help would be highly appreciated.

This is the code I need help with. Trying to pass the latitude etc into the query below, but unable to do it. Looking for the equivalent on ${latitude} in node js...

   latitude := r.URL.Query().Get("lat")
   longitude := r.URL.Query().Get("lon")
   radius := r.URL.Query().Get("rad")


   row := db.QueryRow(`SELECT "name", "website", "coordinates", 
   "description", "rating"
    FROM geospots
    WHERE ST_DWithin("coordinates", ST_MakePoint(latitude = $1, 
   longitude = $2)::geography, radius = $3)`, latitude, longitude)


   Error: 
   andlers/SpotsInArea.go:15:5: latitude declared but not used
   handlers/SpotsInArea.go:16:5: longitude declared but not used
   handlers/SpotsInArea.go:17:5: radius declared but not used

答案1

得分: 3

感谢@mkopirva的指导。

正如你所指出的,你不需要latitude = $1,只需要$1。你在查询中定义了$3,但是缺少了第三个值。

并且请确保你在访问它们的位置内部定义了这些变量。

row := db.QueryRow(`
SELECT
    "name",
    "website",
    "coordinates",
    "description",
    "rating"
FROM
    geospots
WHERE
    ST_DWithin(
        "coordinates",
        ST_MakePoint($1, $2)::geography,
        $3
    )`,
    longitude, latitude, radius
)
英文:

Thanks to @mkopirva

As pointed you don't need latitude = $1 it should be just $1, You have defined $3 in query but missing the 3rd value

And make sure the variable are within the scope where you are accessing them

row := db.QueryRow(`
SELECT
    "name",
    "website",
    "coordinates",
    "description",
    "rating"
FROM
    geospots
WHERE
    ST_DWithin(
        "coordinates",
        ST_MakePoint($1, $2)::geography,
        $3
    )`,
    longitude, latitude, radius
)

huangapple
  • 本文由 发表于 2022年3月2日 23:47:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/71325483.html
匿名

发表评论

匿名网友

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

确定