英文:
Problems using Select in gorp
问题
当我尝试使用gorp进行SELECT操作时,我收到了以下错误信息:
找不到类型为Post的表
以下是我的代码示例:
type Post struct {
Id int64 `db:"post_id"`
CreatedAt int64 `db:"created_at"`
UpdatedAt int64 `db:"updated"`
Title string `db:"title"`
}
var list []*Post
_, err := dbMapper.Select(&list, "SELECT * FROM posts")
if err != nil {
fmt.Fprintf(writer, "%s", err)
return
}
for _, item := range list {
fmt.Fprintf(writer, "%s\n", item.Title)
}
我是这样添加表的:
dbMapper.AddTableWithName(Post{}, "posts").SetKeys(true, "Id")
英文:
I'm receiving the following error when trying to SELECT with gorp:
No table found for type: Post
Here's what my code looks like:
type Post struct {
Id int64 `db:"post_id"`
CreatedAt int64 `db:"created_at"`
UpdatedAt int64 `db:"updated"`
Title string `db:"title"`
}
var list []*Post
_, err := dbMapper.Select(&list, "SELECT * FROM posts")
if (err != nil) {
fmt.Fprintf(writer, "%s", err)
return
}
for _, item := range list {
fmt.Fprintf(writer, "%s\n", item.Title)
}
I'm adding the table like this:
dbMapper.AddTableWithName(Post{}, "posts").SetKeys(true, "Id")
答案1
得分: 1
看起来你没有做什么特别错误的事情。我在本地使用postgres
驱动程序运行了你的示例(你没有指定你使用的是哪个驱动程序),它完全正常工作。我猜测这里可能有一些信息缺失。请确保以下几点:
- 检查在尝试使用表之前是否调用了
dbMapper.AddTableWithName(Post{}, "posts")
。你提到的错误通常是在未调用AddTableWithName
时返回的。 - 检查表在数据库中是否实际存在,并且你是否使用了正确的数据库连接(类似于
sql.Open("postgres", "user=postgres dbname=test")
)。 - 在实例化Gorp时,确保使用了正确的方言:在Postgres的情况下,使用
dbMapper := &gorp.DbMap{Db: db, Dialect: gorp.PostgresDialect{}}
。 - 这可能与较旧版本的Gorp有关-这个问题被问到已经过了几个月,现在升级可能会解决这个问题。
除此之外,我认为我们需要更多的信息来解决这个问题。
英文:
It doesn't seem like you're doing anything particularly wrong. I ran your example locally using the postgres
driver (you didn't specify which driver you are using), and it worked just fine - my guess is that there's some information missing here. Things to make sure of:
- Check that
dbMapper.AddTableWithName(Post{}, "posts")
got called for the table before attempting to use it. The error you refer to is normally returned whenAddTableWithName
was not called. - Check that the table actually exists in your database, and that you're connecting to the correct database with (something like)
sql.Open("postgres", "user=postgres dbname=test")
- When instantiating Gorp, make sure you're using the right dialect:
dbMapper := &gorp.DbMap{Db: db, Dialect: gorp.PostgresDialect{}}
in the case of Postgres - This could be related to an older version of Gorp - it's been a couple of months since this question was asked, upgrading now might resolve the issue.
Other than that I think we'll need more information to get to the bottom of this one.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论