When it comes to working with SQL databases in Node.js, developers often find themselves juggling between raw SQL queries and ORM libraries. But what if there was a library that combined the power of raw SQL with the developer-friendly nature of JavaScript? Well, that's where @databases
comes into play. In this tutorial, we'll explore how to get started with @databases
, install it, and use its features to interact with SQL databases in a modern and efficient way.
Prerequisites
Before we begin, make sure you have the following under your belt:
Basic knowledge of SQL syntax.
Node.js and npm installed on your machine.
Installation
To install @databases
, follow these steps:
Create a New Node.js Project:
Open your terminal and navigate to the directory where you want to create your project. Run the following commands:
Install @databases:
Install
@databases
and its peer dependencies using npm:
In this example, we're installing the PostgreSQL driver for @databases
, but you can use the appropriate driver for your preferred database (e.g., @databases/mysql
for MySQL).
Configuring the Database Connection
Now that you have installed @databases
, the next thing would be to configure the database connection. In your project directory, create a file named db.js
and add the following code:
//db.js
const createConnectionPool = require('@databases/pg');
const pool = new createConnectionPool({
database: 'my-db-app',
user: 'postgres',
password: 'YourPassword',
host: 'localhost',
port: 5432
});
module.exports = pool;
Replace the key values (my-db-app
, postgres
, YourPassword
, etc.) with your actual database connection details.
Basic CRUD Operations
Now that your database connection is set, let's perform some basic CRUD (Create, Read, Update, Delete) operations using @databases
. In your main application file (e.g., index.js
), add the following code:
const pool = require('./db');
const {sql} = require('@databases/pg')
const main = async () => {
try {
// INSERT data into a table
await pool.query(
sql`
INSERT INTO students (id, first_name, last_name)
VALUES (${1},${'Michael'}, ${'Eboji'})`
);
// SELECT data from a table
const student = await pool.query(
sql`
SELECT * FROM students`);
console.log('students:', student);
// UPDATE data in a table
await pool.query(
sql`
UPDATE students
SET first_name = ${'Michael'}
WHERE last_name = ${'Eboji'}`);
// DELETE data from a table
await pool.query(
sql`
DELETE FROM students
WHERE id = ${1}`);
} catch (error) {
console.error('Error:', error);
} finally {
// Close the database connection
await pool.dispose();
}
};
main();
Your output should be like this :
Type Checking and Safety
One of the standout features of @databases
is its integration with TypeScript for type checking and safety. As you noticed in the above examples, queries are tagged template literals. This enables TypeScript to validate query placeholders and prevent SQL injection vulnerabilities.
Conclusion
In this tutorial, we've explored the basics of @databases
and how it can provide a modern and efficient way to interact with SQL databases in Node.js. We covered installation, configuring the database connection, and performing CRUD operations.
With its focus on the developer experience and performance, @databases
is a powerful tool that can simplify database interactions and help you build robust applications.
For more information, check out the official @databases
documentation and explore advanced features and use cases.
Happy coding!