Golang CRUD Operations Using SQL Server: A Step-by-Step Guide

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

Posted on

SQL Server, a powerful and widely-used relational database management system, can be effectively integrated with Go (Golang) to build data-driven applications. In this comprehensive guide, we’ll walk you through the essential steps for performing CRUD (Create, Read, Update, Delete) operations using SQL Server in a Go application. By the end of this article, you’ll have a solid understanding of how to connect to SQL Server, manipulate data, and work with SQL statements.

Prerequisites

Before we begin, 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. SQL Server: SQL Server should be installed and running. You’ll need access to a SQL Server instance with appropriate credentials. Ensure that the SQL Server is reachable from your Go application.

  3. Go SQL Server Driver: To interact with SQL Server from your Go application, you’ll need a SQL Server driver. We’ll use the “github.com/denisenkom/go-mssqldb” package. You can install it using go get:

    go get github.com/denisenkom/go-mssqldb
    

Step 1: Connecting to SQL Server

The first step is establishing a connection to the SQL Server database. Create a function to handle this task:

package main

import (
    "context"
    "database/sql"
    "fmt"
    _ "github.com/denisenkom/go-mssqldb"
)

func connectToSQLServer() (*sql.DB, error) {
    server := "your_server"
    port := 1433
    user := "your_username"
    password := "your_password"
    database := "your_database"

    connString := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d;database=%s", server, user, password, port, database)
    db, err := sql.Open("sqlserver", connString)
    if err != nil {
        return nil, err
    }

    // Ping the SQL Server to ensure connectivity
    err = db.PingContext(context.Background())
    if err != nil {
        return nil, err
    }

    fmt.Println("Connected to SQL Server!")
    return db, nil
}

Replace "your_server", "your_username", "your_password", and "your_database" with your SQL Server connection details.

Step 2: Performing CRUD Operations

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

Create (Insert) Operation

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

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

Read (Query) Operation

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

func queryData(db *sql.DB) ([]User, error) {
    query := "SELECT * FROM users"
    rows, err := db.QueryContext(context.Background(), query)
    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 SQL Server table, create a function like this:

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

Delete Operation

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

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

Step 3: Putting It All Together

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

package main

import (
    "database/sql"
    "fmt"
    "context"
    "log"
)

type User struct {
    ID       int
    Username string
    Email    string
}

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

    // Create a user
    err = insertData(db, "john_doe", "[email protected]")
    if err != nil {
        log.Fatal(err)
    }



    // Read users
    users, err := queryData(db)
    if err != nil {
        log.Fatal(err)
    }
    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
    err = updateData(db, 1, "updated_user", "[email protected]")
    if err != nil {
        log.Fatal(err)
    }

    // Delete a user
    err = deleteData(db, 1)
    if err != nil {
        log.Fatal(err)
    }
}

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

Conclusion

In this step-by-step guide, we’ve covered the basics of performing CRUD operations using SQL Server in a Go application. You’ve learned how to connect to SQL Server, 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. SQL Server’s reliability and Go’s efficiency make them a powerful combination for your projects.