Go GORM CRUD Operations 🎯

beginner
21 min

Go GORM CRUD Operations 🎯

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:

What is ORM (Object-Relational Mapping)? 📝

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.

Introduction to GORM 💡

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.

Installing GORM ✅

First, let's install GORM in our Go workspace:

bash
go get -u github.com/go-gorm/gorm

Creating a Basic Model 📝

A model is a Go struct that represents a table in the database. Here's an example of a simple User model:

go
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"` }

CRUD Operations 🎯

Now, let's dive into the CRUD operations using GORM:

Creating a Record (Create) 💡

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

Reading a Record (Read) 💡

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

Updating a Record (Update) 💡

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

Deleting a Record (Delete) 💡

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

Quiz 📝

Quick Quiz
Question 1 of 1

What does GORM stand for?

Next Steps 💡

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!