Golang CRUD Operations Using SQLite: A Step-by-Step Guide

This article shows steps for performing CRUD (Create, Read, Update, Delete) operations using SQLite in a Go application.

Posted on

SQLite, a lightweight and self-contained relational database management system, is a great choice for building simple and portable data-driven applications with Go (Golang). In this comprehensive guide, we’ll explore the essential steps for performing CRUD (Create, Read, Update, Delete) operations using SQLite in a Go application. By the end of this article, you’ll have a solid understanding of how to connect to SQLite, manipulate data, and work with SQL statements.

Prerequisites

Before we start, 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. SQLite: SQLite is a C library, and Go’s standard library includes a package for interacting with SQLite. You don’t need to install SQLite separately.

Step 1: Creating and Connecting to the SQLite Database

The first step is to establish a connection to the SQLite database. Create a function to handle this task:

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/mattn/go-sqlite3"
)

func connectToSQLiteDB() (*sql.DB, error) {
    db, err := sql.Open("sqlite3", "./mydatabase.db")
    if err != nil {
        return nil, err
    }

    // Ping the database to ensure connectivity
    err = db.Ping()
    if err != nil {
        return nil, err
    }

    fmt.Println("Connected to SQLite Database!")
    return db, nil
}

Replace "./mydatabase.db" with the desired file path for your SQLite database.

Step 2: Performing CRUD Operations

Now that we’re connected to SQLite, let’s dive into CRUD operations.

Create (Insert) Operation

To insert data into a SQLite table, create a function like this:

func insertData(db *sql.DB, username, email string) error {
    _, err := db.Exec("INSERT INTO users (username, email) VALUES (?, ?)", username, email)
    return err
}

Read (Query) Operation

To retrieve data from a SQLite table, create a function like this:

func queryData(db *sql.DB) ([]User, error) {
    rows, err := db.Query("SELECT * FROM users")
    if err != nil {
        return nil, err
    }
    defer rows.Close()

    var users []User
    for rows.Next() {
        var user User
        if err := rows.Scan(&user.ID, &user.Username, &user.Email); err != nil {
            return nil, err
        }
        users = append(users, user)
    }

    return users, nil
}

Update Operation

To update existing data in a SQLite table, create a function like this:

func updateData(db *sql.DB, id int, newUsername, newEmail string) error {
    _, err := db.Exec("UPDATE users SET username = ?, email = ? WHERE id = ?", newUsername, newEmail, id)
    return err
}

Delete Operation

To delete data from a SQLite table, use a function like this:

func deleteData(db *sql.DB, id int) error {
    _, err := db.Exec("DELETE FROM users WHERE id = ?", id)
    return err
}

Step 3: Putting It All Together

Let’s create a simple Go program that connects to SQLite and performs these CRUD operations:

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/mattn/go-sqlite3"
)

type User struct {
    ID       int
    Username string
    Email    string
}

func main() {
    db, err := connectToSQLiteDB()
    if err != nil {
        fmt.Println("Error connecting to SQLite:", err)
        return
    }
    defer db.Close()

    // Create a user
    createUser(db, "john_doe", "[email protected]")

    // Read users
    users, err := queryData(db)
    if err != nil {
        fmt.Println("Error querying users:", err)
        return
    }
    fmt.Println("Users:")
    for _, user := range users {
        fmt.Printf("ID: %d, Username: %s, Email: %s\n", user.ID, user.Username, user.Email)
    }

    // Update a user
    updateUser(db, 1, "updated_user", "[email protected]")

    // Delete a user
    deleteUser(db, 1)
}

This program connects to SQLite, performs CRUD operations, and displays the results.

Conclusion

In this step-by-step guide, we’ve covered the basics of performing CRUD operations using SQLite in a Go application. You’ve learned how to connect to SQLite, insert, query, update, and delete records in a table. These fundamental database operations serve as the foundation for building more complex and data-driven applications in Go. SQLite’s simplicity and portability, combined with Go’s performance and efficiency, make it a great choice for small to medium-sized data-driven applications.