Connecting to a database in Node.js typically involves using a database driver or an Object-Relational Mapping (ORM) library. Below are steps to connect to a relational database using the popular MySQL database as an example. Keep in mind that the process may vary slightly depending on the database system you are using.
Install the MySQL package:
You need to install the MySQL package using npm. Open your terminal and run:
bashnpm install mysql
Require the MySQL module in your Node.js script:
javascriptconst mysql = require('mysql');
Create a connection:
javascriptconst connection = mysql.createConnection({
host: 'localhost', // Replace with your database host
user: 'username', // Replace with your database username
password: 'password', // Replace with your database password
database: 'dbname' // Replace with your database name
});
Connect to the database:
javascriptconnection.connect((err) => {
if (err) {
console.error('Error connecting to database:', err);
return;
}
console.log('Connected to the database');
});
Perform database operations:
After connecting, you can perform various database operations. For example, you can execute SQL queries:
javascriptconnection.query('SELECT * FROM your_table', (err, results) => {
if (err) {
console.error('Error executing query:', err);
return;
}
console.log('Query results:', results);
});
Close the connection:
Once you're done with the database operations, remember to close the connection:
javascriptconnection.end((err) => {
if (err) {
console.error('Error closing connection:', err);
}
console.log('Connection closed');
});
This is a basic example using the MySQL driver. Depending on your database system, you might need a different package (e.g., pg
for PostgreSQL or mongodb
for MongoDB). Additionally, you might consider using an ORM library like Sequelize or Mongoose for more advanced features and abstraction.