如何获得最新的数据在postgresql数据库使用golang光纤编程语言与GORM?



我已经创建了一个结构体

type Humid struct {
Id        int
Sensor_id int
Value     float32
CreateAt  time.Time
}

连接到db

func PostgreSQL() {
dsn := "host=localhost user= password= dbname= port= sslmode=disable TimeZone=Asia/Shanghai"
connection, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
fmt.Println("Connected!")
if err != nil {
panic("Could not connect to database")
}
DB = connection
}

在这个函数中,我想从数据库中获取最新的数据

func WebsoValue(c *fiber.Ctx) error {
var device []Humid
DB.Find(&device)
return c.JSON(device)
}

Raw Query的帮助下,您可以使用Interval获得最新的数据。

下面是您的场景的示例:

func WebsoValue(c *fiber.Ctx) error {

var device []Humid
DB.Raw("SELECT * FROM mytable WHERE created_at >= NOW() - INTERVAL '5 minutes'"
).Scan(&device)
return c.JSON(device)
}

确保在扫描数据时进行错误处理。

最新更新