ตัวอย่างการ Query ข้อมูลจาก Database ด้วย Gorm
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type Products struct {
Id uint
Name string
Price int
On_sale bool
}
type Employees struct {
Emp_no uint
//birth_date *time.Time `gorm:"not null"`
First_name string
Last_name string
Gender string
//hire_date *time.Time `gorm:"not null"`
}
func main() {
dsn := "workshop01:DBpAhVUgCMDSLwwP@tcp(gdsc-int.sit.kmutt.ac.th:13306)/workshop01?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic("fail connection")
} else {
fmt.Println("Connecting successful")
fmt.Println(db)
}
var emp Employees
db.First(&emp)
// SELECT * FROM empolyees ORDER BY id LIMIT 1;
fmt.Println(emp)
db.Take(&emp)
// SELECT * FROM empolyees LIMIT 1;
fmt.Println(emp)
// Get last record, ordered by primary key desc
db.Last(&emp)
// SELECT * FROM empolyees ORDER BY id DESC LIMIT 1;
fmt.Println(emp)
}