Performing CRUD Operations in Angular with Oracle Database

Getting knocked down by errors? Say no more! This tutorial will help you conquer them all.

In this tutorial, we will learn how to create a CRUD (Create, Read, Update, Delete) application using Angular and an Oracle database. We will build a simple angular application where we can add, view, update, and delete data records.


Prerequisites
To follow along with this tutorial, make sure you have the following:

1.Node.js installed on your machine
2.Angular CLI installed (npm install -g @angular/cli)
3.Oracle database installed and configured

Setting up the Angular Project
Let's start by setting up a new Angular project. Open your terminal and run the following commands:

ng new crud-app

cd crud-app

ng g s database

Setting up the Backend Server
Next, we need to set up a backend server to handle the database operations. We will use Express.js and the oracledb package to connect to the Oracle database. Create a new file called server.js in the root of your project directory and add the following code:

npm init -y
npm install express body-parser cors oracledb --save
// server.js

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const oracledb = require('oracledb');

const app = express();
const port = 3000;

// Oracle Database connection configuration
const dbConfig = {
  user: 'system',
  password: 'admin',
  connectString: '//localhost:1521/XE'
};

// Enable CORS
app.use(cors());

// Parse incoming request bodies
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Routes

// Get all records
app.get('/data', (req, res) => {
  oracledb.getConnection(dbConfig, (err, connection) => {
    if (err) {
      console.error(err);
      return res.status(500).json({ error: 'Database connection error' });
    }

    connection.execute('SELECT * FROM employees', (err, result) => {
      connection.close();

      if (err) {
        console.error(err);
        return res.status(500).json({ error: 'Database query error' });
      }

      const records = result.rows.map(row => ({
        id: row[0],
        name: row[1],
        email: row[2]
      }));

      res.json(records);
    });
  });
});

// Create a record
app.post('/data', (req, res) => {
  const { name, email } = req.body;

  if (!name || !email) {
    return res.status(400).json({ error: 'Name and email are required' });
  }

  oracledb.getConnection(dbConfig, (err, connection) => {
    if (err) {
      console.error(err);
      return res.status(500).json({ error: 'Database connection error' });
    }

    connection.execute(
      'INSERT INTO employees (name, email) VALUES (:name, :email)',
      [name, email],
      { autoCommit: true },
      (err, result) => {
        connection.close();

        if (err) {
          console.error(err);
          return res.status(500).json({ error: 'Database query error' });
        }

        res.status(201).json({ message: 'Record created successfully' });
      }
    );
  });
});

// Update a record
app.put('/data/:id', (req, res) => {
  const id = req.params.id;
  const { name, email } = req.body;

  if (!name || !email) {
    return res.status(400).json({ error: 'Name and email are required' });
  }

  oracledb.getConnection(dbConfig, (err, connection) => {
    if (err) {
      console.error(err);
      return res.status(500).json({ error: 'Database connection error' });
    }

    connection.execute(
      'UPDATE employees SET name = :name, email = :email WHERE id = :id',
      [name, email, id],
      { autoCommit: true },
      (err, result) => {
        connection.close();

        if (err) {
          console.error(err);
          return res.status(500).json({ error: 'Database query error' });
        }

        res.json({ message: 'Record updated successfully' });
      }
    );
  });
});

// Delete a record
app.delete('/data/:id', (req, res) => {
  const id = req.params.id;

  oracledb.getConnection(dbConfig, (err, connection) => {
    if (err) {
      console.error(err);
      return res.status(500).json({ error: 'Database connection error' });
    }

    connection.execute(
      'DELETE FROM employees WHERE id = :id',
      [id],
      { autoCommit: true },
      (err, result) => {
        connection.close();

        if (err) {
          console.error(err);
          return res.status(500).json({ error: 'Database query error' });
        }

        res.json({ message: 'Record deleted successfully' });
      }
    );
  });
});

// Start the server
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});


Make sure to replace 'your_username', 'your_password', and 'your_connect_string' with your actual Oracle database credentials.

run the server :
node server.js

Server is running on port 3000.

Implementing the Crud in Angular
Now that we have set up the backend server, let's implement the employee management functionality in our Angular application. Open the employee.component.ts file and replace the code with the following:
// app.component.ts
import { Component, OnInit } from '@angular/core';
import { DatabaseService } from './database.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  records: any[] = [];
  record: any = {};
  isEditing = false;

  constructor(private databaseService: DatabaseService) { }

  ngOnInit() {
    this.loadRecords();
  }

  loadRecords() {
    this.databaseService.getRecords().subscribe(records => {
      this.records = records;
    });
  }

  saveRecord() {
    if (this.isEditing) {
      this.databaseService.updateRecord(this.record.id, this.record.name, this.record.email).subscribe(() => {
        this.resetForm();
        this.loadRecords();
      });
    } else {
      this.databaseService.createRecord(this.record.name, this.record.email).subscribe(() => {
        this.resetForm();
        this.loadRecords();
      });
    }
  }

  editRecord(record: any) {
    this.isEditing = true;
    this.record = { ...record };
  }

  deleteRecord(id: number) {
    this.databaseService.deleteRecord(id).subscribe(() => {
      this.loadRecords();
    });
  }

  resetForm() {
    this.record = {};
    this.isEditing = false;
  }
}

Open the app.component.html file and replace the code with the following:

<!-- app.component.html -->
<h2>CRUD Application</h2>

<!-- Display Records -->
<h3>Records:</h3>
<ul>
  <li *ngFor="let record of records">
    {{ record.id }} - {{ record.name }} - {{ record.email }}
    <button (click)="editRecord(record)">Edit</button>
    <button (click)="deleteRecord(record.id)">Delete</button>
  </li>
</ul>

<!-- Create and Edit Form -->
<h3>Create/Edit Record</h3>
<form #recordForm="ngForm" (ngSubmit)="saveRecord()">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" [(ngModel)]="record.name" required>

  <label for="email">Email:</label>
  <input type="email" id="email" name="email" [(ngModel)]="record.email" required>

  <button type="submit">{{ isEditing ? 'Update' : 'Create' }}</button>
</form>


database.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class DatabaseService {

  private baseUrl = 'http://localhost:3000/data';

  constructor(private http: HttpClient) { }

  getRecords() {
    return this.http.get<any[]>(this.baseUrl);
  }

  createRecord(name: string, email: string) {
    const record = { name, email };
    return this.http.post(this.baseUrl, record);
  }

  updateRecord(id: number, name: string, email: string) {
    const record = { id, name, email };
    return this.http.put(`${this.baseUrl}/${id}`, record);
  }

  deleteRecord(id: number) {
    return this.http.delete(`${this.baseUrl}/${id}`);
  }
}

That's it! You have now implemented a CRUD application using Angular and an Oracle database. You can create, view, update, and delete employee records using the provided interface.
To run the application, open a terminal and navigate to the project directory. Run the following command:

ng serve

Open your browser and visit http://localhost:4200 to access the application.
1-last2345


the code is also available in my github repository:
SQL> describe employees;
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 ID                                        NOT NULL NUMBER
 NAME                                      NOT NULL VARCHAR2(50)
 EMAIL                                     NOT NULL VARCHAR2(100)
Feel free to customize and enhance the application based on your specific requirements.

I hope this tutorial helps you understand how to perform CRUD operations in Angular with an Oracle database. Enjoy building your employee management system!

Post a Comment

0 Comments