Golang pq: 执行 SQL 时出现语法错误

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

Golang pq: syntax error when executing sql

问题

使用revelgolang 1.1.2gorppostgres 9.3.2heroku上。

参考robfig的列表booking example

func (c App) ViewPosts(page int) revel.Result {
    if page == 0 {
        page = 1
    }
    var posts []*models.Post
    size := 10
    posts = loadPosts(c.Txn.Select(models.Post{},
        `select * from posts offset ? limit ?`, (page-1)*size, size)) // error here
    return c.RenderJson(posts)
}

不确定为什么会出现pq: syntax error at or near "limit"。我猜测组合查询可能有问题。为什么查询结果不是像select * from posts offset 0 limit 10这样的形式,我已经在postgres上测试过可以运行。我在哪里搞错了?

英文:

Using revel, golang 1.1.2, gorp, postgres 9.3.2 on heroku

Following robfig's List booking example

func (c App) ViewPosts(page int) revel.Result {
    if page == 0 {
        page = 1
    }
    var posts []*models.Post
    size := 10
    posts = loadPosts(c.Txn.Select(models.Post{},
        `select * from posts offset ? limit ?`, (page-1)*size, size)) // error here
    return c.RenderJson(posts)
}

Not sure why I'm getting pq: syntax error at or near "limit". I'm assuming the combined query is wrong. Why does the query not end up being something like select * from posts offset 0 limit 10, which I've tested to run on postgres. Where am I messing up?

答案1

得分: 24

我不熟悉Postgres,但我找到了这个问题。我认为你应该像godoc中的示例那样使用它。

godoc中的示例

age := 21
rows, err := db.Query("SELECT name FROM users WHERE age = $1", age)

(将"?"替换为"$n")

你的代码

func (c App) ViewPosts(page int) revel.Result {
if page == 0 {
    page = 1
}
var posts []*models.Post
size := 10
posts = loadPosts(c.Txn.Select(models.Post{},
    `select * from posts offset $1 limit $2`, (page-1)*size, size))
return c.RenderJson(posts)
}
英文:

I'm not familiar with postgres, but I found this issue. I think you should use it like in the godoc

Example in godoc

age := 21
rows, err := db.Query("SELECT name FROM users WHERE age = $1", age)

(Replace "?" with "$n")

Your code

func (c App) ViewPosts(page int) revel.Result {
if page == 0 {
    page = 1
}
var posts []*models.Post
size := 10
posts = loadPosts(c.Txn.Select(models.Post{},
    `select * from posts offset $1 limit $2`, (page-1)*size, size))
return c.RenderJson(posts)
}

huangapple
  • 本文由 发表于 2014年1月12日 18:36:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/21073650.html
匿名

发表评论

匿名网友

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

确定