How to Use MariaDB Database in Go with GORM: A Step-by-Step Guide

In this comprehensive guide, we’ll walk you through the essential steps for setting up GORM with MariaDB in a Go application.

Posted on

MariaDB, a popular open-source relational database system, can be seamlessly integrated with Go (Golang) using the GORM library. GORM simplifies database interactions by providing an Object-Relational Mapping (ORM) framework. In this comprehensive guide, we’ll walk you through the essential steps for setting up GORM with MariaDB in a Go application. By the end of this article, you’ll have a solid understanding of how to connect to MariaDB, define models, perform CRUD (Create, Read, Update, Delete) operations, and leverage GORM’s powerful features.

Prerequisites

Before we get started, make sure you have the following prerequisites in place:

  1. Go Environment: Install Go if you haven’t already. You can download it from the official Go website.

  2. MariaDB Server: MariaDB should be installed and running. Ensure that you have access to a MariaDB database instance with the necessary credentials. Make sure the MariaDB server is reachable from your Go application.

  3. GORM Library: Install the GORM library using go get:

    go get -u gorm.io/gorm
    go get -u gorm.io/driver/mysql
    

Step 1: Setting Up the GORM Environment

The first step is to set up the GORM environment in your Go project. Create a Go file (e.g., main.go) and import the necessary packages:

package main

import (
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "log"
)

Step 2: Connecting to the MariaDB Database

Next, establish a connection to the MariaDB database using GORM. Create a function to handle this task:

func connectToMariaDB() (*gorm.DB, error) {
    dsn := "username:password@tcp(localhost:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err != nil {
        return nil, err
    }

    return db, nil
}

Replace "username", "password", "localhost", "3306", and "dbname" with your MariaDB credentials and database details.

Step 3: Defining Models

In GORM, models represent database tables. Define your models as Go structs with appropriate field tags to map them to MariaDB columns. For example, let’s create a “User” model:

type User struct {
    ID       uint   `gorm:"primaryKey"`
    Username string `gorm:"unique"`
    Email    string
}

Step 4: Migrating the Database

GORM provides an automatic database migration feature that creates tables based on your model definitions. In your main function, call the AutoMigrate function to perform this migration:

func main() {
    db, err := connectToMariaDB()
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    // Perform database migration
    err = db.AutoMigrate(&User{})
    if err != nil {
        log.Fatal(err)
    }

    // Your CRUD operations go here
}

This code ensures that the “User” table is created in the MariaDB database.

Step 5: Performing CRUD Operations

Now, let’s perform CRUD operations using GORM. Here are some examples:

Create (Insert) Operation

func createUser(db *gorm.DB, user *User) error {
    result := db.Create(user)
    if result.Error != nil {
        return result.Error
    }
    return nil
}

Read (Query) Operation

func getUserByID(db *gorm.DB, userID uint) (*User, error) {
    var user User
    result := db.First(&user, userID)
    if result.Error != nil {
        return nil, result.Error
    }
    return &user, nil
}

Update Operation

func updateUser(db *gorm.DB, user *User) error {
    result := db.Save(user)
    if result.Error != nil {
        return result.Error
    }
    return nil
}

Delete Operation

func deleteUser(db *gorm.DB, user *User) error {
    result := db.Delete(user)
    if result.Error != nil {
        return result.Error
    }
    return nil
}

Step 6: Putting It All Together

Let’s create a simple Go program that connects to MariaDB, performs CRUD operations, and displays the results:

func main() {
    db, err := connectToMariaDB()
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    // Perform database migration
    err = db.AutoMigrate(&User{})
    if err != nil {
        log.Fatal(err)
    }

    // Create a user
    newUser := &User{Username: "john_doe", Email: "[email protected]"}
    err = createUser(db, newUser)
    if err != nil {
        log.Fatal(err)
    }
    log.Println("Created User:", newUser)

    // Query user by ID
    userID := newUser.ID
    user, err := getUserByID(db, userID)
    if err != nil {
        log.Fatal(err)
    }
    log.Println("User by ID:", user)

    // Update user
    user.Email = "[email protected]"
    err = updateUser(db, user)
    if err != nil {
        log.Fatal(err)
    }
    log.Println("Updated User:", user)

    // Delete user
    err = deleteUser(db, user)
    if err != nil {
        log.Fatal(err)
    }
    log.Println("Deleted User:", user)
}

This program connects to MariaDB, performs CRUD operations, and logs the results.

Conclusion

In this step-by-step guide, we’ve explored how to use MariaDB database in Go with GORM. You’ve learned how to set up GORM, connect to a MariaDB database, define models, perform automatic database migration, and execute CRUD operations. GORM simplifies database interactions in your Go applications, making it a powerful tool for building data-driven solutions with MariaDB.