Using GORM with SQLite

Hossein MarganiHossein Margani
3 min read

When it comes to working with databases in Go, GORM is one of the most popular ORM (Object-Relational Mapping) libraries. It simplifies database interactions by allowing you to work with Go structs instead of writing raw SQL queries. SQLite, on the other hand, is a lightweight, file-based database that’s perfect for small projects or prototyping. Combining GORM with SQLite can make your development process smoother and faster.

To get started, you’ll need to install GORM and the SQLite driver. You can do this using Go modules. Run the following command in your terminal:

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

Once the packages are installed, you can start using GORM with SQLite. First, import the necessary packages and define a model. A model in GORM is a Go struct that represents a table in the database. Here’s an example:

package main

import (
    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
)

type User struct {
    ID   uint
    Name string
    Age  int
}

func main() {
    db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }

    db.AutoMigrate(&User{})
}

In this example, we define a User struct and use db.AutoMigrate to automatically create the corresponding table in the SQLite database. The database file, test.db, will be created in the same directory as your Go program.

Once your database and table are set up, you can start performing CRUD (Create, Read, Update, Delete) operations. Here’s how you can insert a new record:

user := User{Name: "John", Age: 30}
db.Create(&user)

To query the database, you can use GORM’s methods like First, Find, and Where. For example, to retrieve the first user with the name "John":

var result User
db.First(&result, "name = ?", "John")

Updating and deleting records is just as straightforward. To update a user’s age:

db.Model(&User{}).Where("name = ?", "John").Update("age", 31)

And to delete a user:

db.Delete(&User{}, "name = ?", "John")

To fetch a user by their ID using GORM, you can use the First method. This method allows you to query the database and retrieve the first record that matches the given conditions. Here’s how you can get a user by their ID:

// Define a variable to hold the user record
record := &User{ID: 10}

// Query the database for the user with ID 10
db.First(record)

// Check if the record was found
if record.ID != 0 {
    fmt.Printf("User found: %+v\n", record)
} else {
    fmt.Println("User not found")
}

In this example, record is initialized with the ID of the user you want to retrieve. When db.First(record) is called, GORM will query the database for a user with the specified ID. If the user is found, the record variable will be populated with the user’s data. If no user is found, the ID field will remain 0, which you can use to check if the record exists.

This approach is clean and concise, leveraging GORM’s ability to work directly with structs. It’s a great way to fetch specific records without writing complex queries.

GORM’s simplicity and SQLite’s lightweight nature make them a great combination for small-scale applications or when you need a quick and easy database solution. With just a few lines of code, you can set up your database, define models, and perform CRUD operations without worrying about the underlying SQL.

0
Subscribe to my newsletter

Read articles from Hossein Margani directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Hossein Margani
Hossein Margani