希望从我的 postgresql 数据库中检索表名。现在,我知道在 Go 中您可以使用 sql 和 pq 驱动程序,但我使用 GORM 在 REST API 中执行查询。
PostgreSQL中的table_name类型是“information_schema.sql_identifier”。这就是我试图做的,但类型不是字符串。
var tables []string
if err := db.Table("information_schema.tables").Select("table_name").Where("table_schema = ?", "public").Find(&tables).Error; err != nil {
panic(err)
}
最佳答案
TL;DR
要使用 Gorm 将单个列值选择到 slice 中,您可以使用 db.Pluck
帮助程序:
var tables []string
if err := db.Table("information_schema.tables").Where("table_schema = ?", "public").Pluck("table_name", &tables).Error; err != nil {
panic(err)
}
TS;WM
考虑到这一点,SELECT 语句返回一组具有一个或多个列的行。为了将它们映射到 Go 代码,我们需要一种结构体,以便 Gorm 可以理解哪一列映射到该结构体的哪个字段。即使您只选择 1 个单列,它也只是一个具有 1 个单字段的结构。
type Table struct {
TableName string
// more fields if needed...
}
所以你的输出变量应该是[]*Table
:
var tables []*Table
if err := db.Table("information_schema.tables").Select("table_name").Where("table_schema = ?", "public").Find(&tables).Error; err != nil {
panic(err)
}
注意:如果您不想修改 slice 内的元素,也可以是 []Table
。
如果您不想定义结构,可以使用db.Pluck
函数,它只是此类代码的帮助器:
rows, err := db.Table("information_schema.tables").Select("table_name").Where("table_schema = ?", "public").Rows()
defer rows.Close()
var tables []string
var name string
for rows.Next() {
row.Scan(&name)
tables = append(tables, name)
}
关于go - 使用 GORM 从 Postgresql 检索表名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60976342/