Database connectivity lets your Node.js app talk to a database to save and get data. Without it, your app can't remember or use information.
0
0
Why database connectivity matters in Node.js
Introduction
When you want to save user sign-up details like names and emails.
When you need to show a list of products stored in a database.
When your app must update information, like changing a password.
When you want to keep track of user actions or logs.
When you need to fetch data quickly for reports or dashboards.
Syntax
Node.js
const { Client } = require('pg');
async function main() {
const client = new Client({
user: 'user',
host: 'localhost',
database: 'mydb',
password: 'password',
port: 5432
});
await client.connect();
// Use client to query the database
await client.end();
}
main().catch(console.error);This example uses the 'pg' library to connect to a PostgreSQL database.
You create a client with connection details, connect, run queries, then close the connection.
Examples
Example connecting to a MySQL database using the mysql2/promise library.
Node.js
const mysql = require('mysql2/promise'); async function main() { const connection = await mysql.createConnection({ host: 'localhost', user: 'root', database: 'testdb', password: 'password' }); // Run queries here await connection.end(); } main().catch(console.error);
Example connecting to a MongoDB database using the official MongoDB driver with async/await.
Node.js
import { MongoClient } from 'mongodb'; const uri = 'mongodb://localhost:27017'; const client = new MongoClient(uri); async function run() { await client.connect(); const database = client.db('mydb'); const collection = database.collection('users'); // Use collection to find or insert documents await client.close(); } run();
Sample Program
This Node.js program connects to a PostgreSQL database, asks for the current time, prints it, then closes the connection.
Node.js
import { Client } from 'pg'; async function main() { const client = new Client({ user: 'user', host: 'localhost', database: 'mydb', password: 'password', port: 5432 }); await client.connect(); const res = await client.query('SELECT NOW()'); console.log('Current time from database:', res.rows[0].now); await client.end(); } main().catch(console.error);
OutputSuccess
Important Notes
Always close your database connection to avoid resource leaks.
Use async/await to handle database calls cleanly and avoid callback hell.
Keep your database credentials safe and do not hardcode them in real apps.
Summary
Database connectivity lets your app save and get data.
You connect, run queries, then close the connection.
It is important for apps that need to remember or update information.