Welcome to this comprehensive guide on Go GORM CRUD Operations! By the end of this lesson, you'll be able to perform Create, Read, Update, and Delete (CRUD) operations using GORM - a popular Go ORM library.
Let's start with the basics:
ORM is a technique that allows us to interact with databases using objects (Go structs, in our case) instead of SQL queries. This simplifies our code and makes it more maintainable and scalable.
GORM is an open-source Go ORM library that supports multiple databases, including MySQL, PostgreSQL, SQLite, and more. It's easy to use and provides an intuitive and powerful API for working with databases.
First, let's install GORM in our Go workspace:
go get -u github.com/go-gorm/gormA model is a Go struct that represents a table in the database. Here's an example of a simple User model:
type User struct {
ID uint `json:"id" gorm:"primary_key"`
Name string `json:"name" gorm:"type:varchar(100)"`
Email string `json:"email" gorm:"type:varchar(100);unique"`
Age int `json:"age" gorm:"type:int"`
}Now, let's dive into the CRUD operations using GORM:
import (
"fmt"
"github.com/go-gorm/gorm"
)
func main() {
db, err := gorm.Open("sqlite3", "./gorm.db")
if err != nil {
fmt.Println("Failed to connect to the database:", err)
return
}
defer db.Close()
user := User{Name: "John Doe", Email: "john.doe@example.com", Age: 30}
db.Create(&user)
fmt.Println("User created with ID:", user.ID)
}func main() {
db, err := gorm.Open("sqlite3", "./gorm.db")
if err != nil {
fmt.Println("Failed to connect to the database:", err)
return
}
defer db.Close()
var user User
db.First(&user, 1)
fmt.Println("User found:", user)
}func main() {
db, err := gorm.Open("sqlite3", "./gorm.db")
if err != nil {
fmt.Println("Failed to connect to the database:", err)
return
}
defer db.Close()
var user User
db.First(&user, 1)
user.Name = "Jane Doe"
db.Save(&user)
fmt.Println("User updated:", user)
}func main() {
db, err := gorm.Open("sqlite3", "./gorm.db")
if err != nil {
fmt.Println("Failed to connect to the database:", err)
return
}
defer db.Close()
var user User
db.First(&user, 1)
db.Delete(&user)
fmt.Println("User deleted:", user)
}What does GORM stand for?
Now that you have a solid understanding of CRUD operations with GORM, you can explore more advanced features such as associations, transactions, and migrations. Happy coding!