Basic Usage of SQLite in a Golang Application

In this article, we’ll explore the fundamental aspects of using SQLite in a Go application, including creating a database, performing CRUD (Create, Read, Update, Delete) operations.

Posted on

SQLite is a lightweight and self-contained relational database management system, while Go (often referred to as Golang) is a versatile and efficient programming language. Integrating SQLite with Go allows you to build simple and portable data-driven applications. In this article, we’ll explore the fundamental aspects of using SQLite in a Go application, including creating a database, performing CRUD (Create, Read, Update, Delete) operations, and handling SQLite-specific features.

Prerequisites

Before we dive into the code, 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.

Creating and Connecting to an SQLite Database

The first step in using SQLite with Go is creating and connecting to the database. SQLite is a file-based database, so you’ll need to specify a file path for your database file. Here’s how to create and connect to an SQLite database:

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.

Performing CRUD Operations

Now that you’ve connected to SQLite, you can perform CRUD operations. Let’s explore some common database operations.

Creating a Table

Before you can perform CRUD operations, you need to create a table. Here’s an example of how to create a simple table:

func createTable(db *sql.DB) error {
    _, err := db.Exec(`
        CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY,
            username TEXT,
            email TEXT
        )
    `)
    return err
}

Inserting Data (Create)

To insert data into an SQLite table, use 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
}

Querying Data (Read)

To retrieve data from an 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
}

Updating Data (Update)

To update existing data in an 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
}

Deleting Data (Delete)

To delete data from an 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
}

Conclusion

In this article, we’ve explored the basics of using SQLite in a Go application. You’ve learned how to create and connect to an SQLite database, create tables, and perform CRUD operations (Create, Read, Update, Delete). SQLite’s simplicity and portability, combined with Go’s performance and efficiency, make it a great choice for building small to medium-sized data-driven applications.