Skip to main content

ตัวอย่างการ Query ข้อมูลจาก Database ด้วย Gorm

Query without condition

image.png

คำสั่ง query {First, Take, Last}

First จะทำการ order table และ query เอาตัวแรกสุด(index 1)ของ table 

Take จะทำการ query ข้อมูลของ table โดยจะ limit เอาแค่ตัวเดียว

Last  จะทำการ order table และ query เอาตัวสุดท้าย (index last)ของ table 

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)
}

image.png

Query with condition 

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, 10054)
	// SELECT * FROM empolyees WHERE emp_no = 10054;
	fmt.Println(emp)

	db.Find(&emp, []int{10059, 10052, 10056})
	// SELECT * FROM empolyees WHERE emp_no in 10059, 10052, 10056;
	fmt.Println(emp)

	db.First(&emp, "First_name = ?", "Leon")
	// SELECT * FROM empolyees WHERE First_name = "Leon";
	fmt.Println(emp)
}

image.png