Golang
Golang

 

Introduction

In this tutorial, we will create a simple Employee Database with CRUD (Create, Read, Update, Delete) operations using the Go programming language. This project will allow you to manage employee records and perform basic database operations such as adding new employees, viewing existing employees, updating their details, and deleting records.

Objective

The objective of this program is to provide a simple and clear demonstration of how CRUD operations can be implemented in Go for managing employee data. By the end of this tutorial, you should be able to:

  • Understand the basic structure of a Go program for database management.
  • Implement Create, Read, Update, and Delete operations.
  • Store and manage employee data in a Go-based application.

Employee Database Program Code in Go


package main

import (
    "fmt"
    "log"
    "os"
    "encoding/json"
    "io/ioutil"
    "strings"
)

type Employee struct {
    ID       int    `json:"id"`
    Name     string `json:"name"`
    Position string `json:"position"`
    Salary   float64 `json:"salary"`
}

var employees []Employee
var dbFile = "employee_data.json"

// Read employees from the file
func readEmployees() {
    file, err := os.Open(dbFile)
    if err != nil {
        log.Println("Error opening file:", err)
        return
    }
    defer file.Close()

    data, err := ioutil.ReadAll(file)
    if err != nil {
        log.Println("Error reading file:", err)
        return
    }

    err = json.Unmarshal(data, &employees)
    if err != nil {
        log.Println("Error unmarshalling data:", err)
    }
}

// Write employees to the file
func writeEmployees() {
    data, err := json.MarshalIndent(employees, "", "    ")
    if err != nil {
        log.Println("Error marshalling data:", err)
        return
    }

    err = ioutil.WriteFile(dbFile, data, 0644)
    if err != nil {
        log.Println("Error writing to file:", err)
    }
}

// Add new employee
func addEmployee(id int, name, position string, salary float64) {
    employee := Employee{
        ID:       id,
        Name:     name,
        Position: position,
        Salary:   salary,
    }
    employees = append(employees, employee)
    writeEmployees()
}

// Get employee by ID
func getEmployeeByID(id int) *Employee {
    for _, employee := range employees {
        if employee.ID == id {
            return &employee
        }
    }
    return nil
}

// Update employee by ID
func updateEmployee(id int, name, position string, salary float64) {
    for i, employee := range employees {
        if employee.ID == id {
            employees[i].Name = name
            employees[i].Position = position
            employees[i].Salary = salary
            writeEmployees()
            return
        }
    }
    log.Println("Employee with ID", id, "not found.")
}

// Delete employee by ID
func deleteEmployee(id int) {
    for i, employee := range employees {
        if employee.ID == id {
            employees = append(employees[:i], employees[i+1:]...)
            writeEmployees()
            return
        }
    }
    log.Println("Employee with ID", id, "not found.")
}

// Display all employees
func displayEmployees() {
    if len(employees) == 0 {
        fmt.Println("No employees found.")
        return
    }

    fmt.Println("Employee List:")
    for _, employee := range employees {
        fmt.Printf("ID: %d, Name: %s, Position: %s, Salary: %.2f\n", employee.ID, employee.Name, employee.Position, employee.Salary)
    }
}

// Main program
func main() {
    readEmployees()

    for {
        fmt.Println("\nEmployee Database Menu:")
        fmt.Println("1. Add Employee")
        fmt.Println("2. View All Employees")
        fmt.Println("3. Update Employee")
        fmt.Println("4. Delete Employee")
        fmt.Println("5. Exit")
        fmt.Print("Choose an option: ")

        var choice int
        fmt.Scan(&choice)

        switch choice {
        case 1:
            var id int
            var name, position string
            var salary float64

            fmt.Print("Enter ID: ")
            fmt.Scan(&id)
            fmt.Print("Enter Name: ")
            fmt.Scan(&name)
            fmt.Print("Enter Position: ")
            fmt.Scan(&position)
            fmt.Print("Enter Salary: ")
            fmt.Scan(&salary)

            addEmployee(id, name, position, salary)
        case 2:
            displayEmployees()
        case 3:
            var id int
            var name, position string
            var salary float64

            fmt.Print("Enter Employee ID to Update: ")
            fmt.Scan(&id)
            fmt.Print("Enter New Name: ")
            fmt.Scan(&name)
            fmt.Print("Enter New Position: ")
            fmt.Scan(&position)
            fmt.Print("Enter New Salary: ")
            fmt.Scan(&salary)

            updateEmployee(id, name, position, salary)
        case 4:
            var id int
            fmt.Print("Enter Employee ID to Delete: ")
            fmt.Scan(&id)
            deleteEmployee(id)
        case 5:
            fmt.Println("Exiting...")
            return
        default:
            fmt.Println("Invalid choice, please try again.")
        }
    }
}
            

Program Explanation

The program is designed to manage employee records using a JSON file as a database. Here’s a breakdown of how it works:

  • Struct Definition: We define an Employee struct to represent each employee’s details such as ID, Name, Position, and Salary.
  • Read and Write Functions: The readEmployees() and writeEmployees() functions handle reading from and writing to a JSON file.
  • CRUD Functions: Functions such as addEmployee(), getEmployeeByID(), updateEmployee(), and deleteEmployee() perform the respective CRUD operations on employee data.
  • Main Menu: The main program loop displays a menu and allows the user to choose which operation to perform (Add, View, Update, Delete, or Exit).

How to Run the Program

Follow these steps to run the program:

  1. Make sure you have Go installed on your machine. You can download it from here.
  2. Save the code above into a file, for example, employee_db.go.
  3. Open your terminal or command prompt and navigate to the directory where the file is saved.
  4. Run the program using the following command:
    go run employee_db.go
  5. The program will start and display the menu. You can interact with it to manage employee data.
© 2025 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)