How to connect a Database With JavaScript: Creating a Simple CRUD System With JavaScript
By Ahmad Afan shobari

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)
npm i pg
npm i readline/promise (optional)
2. Create DataBase on Postgres
Second, we need database to save data from query
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:
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:
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:
//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:

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:
//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:

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:
//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:

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:
//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:

last, we will create a file to running all previes file
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
4. Publish Into Github
then we will publish this project into github
first we create new repository on github

this a display from we repository

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

than we paste to directory which we need, example this

git clone "use the paste"
than we will move some previous file it into this repository

than we can commit and push to repository


finally, we success to create connecting database project
4. Closing
thanks for watching, and see you next time



