# How to connect a Database With JavaScript: Creating a Simple CRUD System With JavaScript

Assalamualaikum, hello guys in this article we will connect a database with javascript, than create a simple crud system with javascript.

# 1\. Install Package on NPM

First, we need some a package:

* pg
    
* readline/promise (default available in node.js)
    

```bash
npm i pg
npm i readline/promise (optional)
```

# 2\. Create DataBase on Postgres

Second, we need database to save data from query

```bash
create database school;

create table students (
id serial primary key,
name varchar(100) not null,
address varchar(150) not null
);
```

# 3\. Create a File & CRUD with the file

## 3.1 Create a File to Save Package Pg

Third, we will create a file name is `db.js` on folder utils, and add this code:

```javascript
import pg from 'pg';
 
const pool = new pg.Pool({
  user: 'postgres',
  host: 'localhost',
  database: 'school',
  password: '<your_password>',
  port: 5432,
});

export default pool;
```

## 3.2 Create a File to Save Package Readline

Fourth, we will create a file name is rideline.js on folder utils, and add this code:

```javascript
import readline from 'node:readline/promises';
import {stdin as input, stdout as output } from 'node:process';

const rl = readline.createInterface({input, output})

export async function inputData(question){
    const answer = await rl.question(`${question}`)
    return answer.trim()
}

export async function closeInput() {
    await rl.close();
}
```

## 3.3 Create System Create Data

Fifth, we will create a file to system create data for database name file is `1-create.js`, add this code:

```javascript
//file 1-create.js
import pool from './utils/db.js';
import {inputData, closeInput} from './utils/app.js'
 
export default async function addStudent() {
  try {
    const queryText = `
    INSERT INTO students(name, address) VALUES($1, $2) RETURNING *
    `;
    const res = await pool.query(
    queryText, 
    [studentName, studentAddress]
    );
 
    console.log('new student success add on database:');
    console.log(res.rows[0]); 
  } catch (err) {
    console.error('failed add student data:', err.stack);
  } finally {
    await pool.end();
    await closeInput();
  }
}

addStudent();
```

when you running in terminal, display this:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1758374615366/589fd786-26c5-4bee-bf6f-3f3fc32aaa83.png align="center")

## 2.4 Create System Read Data

Sixth, we will create a file to system read data for database name file is `2-read.js`, add this code:

```javascript
//file 2-read.js
import pool from './utils/db.js';
export default async function seeStudent() {
  try {
    const res = await pool.query('
    SELECT * FROM student ORDER BY id ASC
    ');
 
    if (res.rows.length === 0) {
      console.log('not found student data.');
      return;
    }
 
    console.log('data student:');
    res.rows.forEach(santri => {
      console.log(
    `ID: ${santri.id}, 
    Name: ${student.name}, 
    address: ${student.address}`);
    });
 
  } catch (err) {
    console.error('failed ride data student:', err.stack);
  } 
}
 
seeStudent();
```

when we running this, display this:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1758375200409/a1f1edb8-4418-4c37-80e2-2a786eb59a57.png align="center")

## 3.5 Create System Update Data

Seventh, we will create a file to system update data for database name file is `3-update.js`, add this code:

```javascript
//file 3-update.js
import pool from './utils/db.js';
import {inputData, closeInput} from './utils/app.js'

export default async function updateStudent() {
  try {
    const res = await pool.query(
    'UPDATE students SET nama = $1, alamat = $2 WHERE id = $3', 
    [choice_name, choice_address, choice_id]
    );
    
    console.log('new student success add on database:');
    console.log(res.rows[choice_id]);
  } catch (err) {
    console.error('failed update data student:', err.stack);
  }
}
 
updateStudent();
```

when we running this, display this:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1758375692215/21227a07-ddd3-4648-b84d-fb88e9404386.png align="center")

## 3.6 Create System Delete Data

Eighth, we will create a file to system update data for database name file is `4-delete.js`, add this code:

```javascript
//file 4-delete.js
import pool from './utils/db.js';
import {inputData, closeInput} from './utils/app.js'

export default async function deleteStudent() {
  try {

    const queryText = await pool.query('
    DELETE FROM students WHERE id = $1', [choice_id]
    );
    
    console.log('new student success add on database:');
  } catch (err) {
    console.error('failed delete data student:', err.stack);
  } 
}
 
deleteStudent();
```

when we running this, display this:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1758376030359/1ca54cdb-1ce8-4470-b8cf-05314addcfd1.png align="center")

last, we will create a file to running all previes file

```javascript
import { inputData, closeInput } from './utils/readline.js';
import pool from './utils/db.js';
import addStudent from './1-create.js';
import seeStudent from './2-read.js';
import updateStudent from './3-update.js';
import deleteStudent from './4-delete.js';

function showMenu() {
  console.log("\n=== DATEABASE SERVICES ===");
  console.log("1) Create Database");
  console.log("2) Read Database");
  console.log("3) Update Database");
  console.log("4) Delete Database");
  console.log("0) Close Shop");
}

async function askCreate() {
  const nameStudent = await inputData("student name?");
  const addressStudent = await inputData('student address?');
  await tambahSantri(nameStudent, addressStudent);
}


async function askUpdate() {
  const choice_id = await inputData("how much id update:");
  const choice_name = await inputData("new name?:")
  const choice_address = await inputData("new address?")
  await updateSantri(choice_id, choice_name, choice_address);
}

async function askDelete() {
  const choice_id = await inputData("how much id will delete:");
  await deleteSantri(choice_id);
}

async function serviceLoop() {
  while (true) {
    showMenu();
    const choice = await inputData("Choose a CRUD Database (number): ");

    switch (choice) {
      case "1":
        await askCreate();
        break;

      case "2":
        await seeStudent()
        break;

      case "3":
        await askUpdate()
        break;

      case "4":
        await askDelete()
        break

      case "0":
        console.log("\nShop closed. Thank you.\n");
        await pool.end()
        await closeInput()
        return;

      default:
        console.log("Invalid choice. Please try again.\n");
    }
  }
}

serviceLoop();
```

this a display from `app.js`

![]( align="center")

# 4\. Publish Into Github

then we will publish this project into github

first we create new repository on github

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1758508544038/c2624283-6abc-420e-b2b9-41a08afa6ce0.png align="center")

this a display from we repository

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1758508687539/03429d72-8a73-4699-b6ca-d915c66e389b.png align="center")

then we need clone repository into we the device, copy ssh

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1758508608249/fb29f84b-1833-4094-8fc7-3a018295d078.png align="center")

than we paste to directory which we need, example this

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1758508769521/909e480b-1d66-4cfe-9ee3-c335eabae8b9.png align="center")

```bash
git clone "use the paste"
```

than we will move some previous file it into this repository

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1758509133345/0c89d1d1-198d-4658-b8a0-5a9458dd137a.png align="center")

than we can commit and push to repository

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1758509854957/af1e8507-975e-4164-87f4-faaff61bee73.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1758509877810/dccdf0a3-a808-4c0e-a47d-c550c3bdf7ff.png align="center")

finally, we success to create connecting database project

# 4\. Closing

thanks for watching, and see you next time
