Welcome to the world of Go programming, where we'll be diving into using the GORM ORM (Object-Relational Mapping) tool! In this lesson, we'll learn about GORM from scratch, making it easy for both beginners and intermediate learners.
GORM is an open-source Go ORM library that allows you to work with databases using a simple, elegant, and developer-friendly Go API. It simplifies the process of interacting with databases, making it easier to write, understand, and maintain your code.
To install GORM, first, you need to have Go installed on your system. You can check if you have Go by running go version in your terminal. If it's not installed, you can download it from the official Go website.
Once you have Go installed, you can install GORM using the following command:
go get -u gorm.io/gormLet's start by creating a simple connection to a SQL database. Here's an example of how to connect to a MySQL database:
package main
import (
"github.com/go-sql-driver/mysql"
"gorm.io/gorm"
)
func main() {
db, err := gorm.Open(mysql.Open("username:password@tcp(localhost:3306)/dbname"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
// ... your code here
}š” Pro Tip: Replace username, password, and dbname with your actual database credentials and database name.
In GORM, models represent tables in your database. Let's create a simple User model:
type User struct {
gorm.Model
Name string
Age int
}š Note: The gorm.Model is a predefined struct that includes common database fields like ID, CreatedAt, and UpdatedAt.
Now that we have our User model, let's create a new record:
user := User{Name: "John Doe", Age: 25}
db.Create(&user)This code creates a new User with the name "John Doe" and age 25 and saves it to the database.
To read records, we can use the Find() method:
var user User
db.First(&user, 1)This code retrieves the user with an ID of 1 and saves it to the user variable.
To update a record, we can use the Save() method:
user.Name = "John Updated"
db.Save(&user)This code updates the user's name to "John Updated" and saves the changes to the database.
To delete a record, we can use the Delete() method:
db.Delete(&user)This code deletes the user record from the database.
What does the `gorm.Model` struct include in GORM?
That's it for this lesson! In the next lesson, we'll dive deeper into GORM, covering topics like associations, transactions, and more. Stay tuned! šÆ