Connect to Databases With Sequelize

Sequelize·5 min read·Jan 1, 2025

The Sequelize ORM is available on the npm registry through the sequelize package. To function properly, Sequelize requires an additional component called a database driver that allows it to interact with your database type.

$ npm install --save sequelize pg pg-hstore # Postgres
$ npm install --save sequelize mysql2       # MySQL
$ npm install --save sequelize mariadb      # MariaDB
$ npm install --save sequelize sqlite3      # SQLite
$ npm install --save sequelize tedious      # Microsoft SQL Server
$ npm install --save sequelize oracledb     # Oracle Database

Create a database connection handler

To create a new database handler, you can instantiate the Sequelize class exported by the sequelize module using the following parameters:

const { Sequelize } = require('sequelize');

const db = new Sequelize(name, user, password, {
  host,
  port,
  dialect
});

Where:

  • name is the name of the database you want to connect to.
  • user is the name of the database user you want to connect as.
  • password is the password of the specified user.
  • host is the IP address of the machine the database is running on (e.g., '127.0.0.1').
  • port is the port the database is listening to (e.g., 3306 for MySQL, 5432 for PostgreSQL).
  • dialect is the type of database used, including: 'mysql', 'postgres', 'sqlite', 'mariadb', 'mssql', 'db2', 'snowflake', 'oracle'.

Example

Let's consider this script, that creates a new connection handler to the learn_backend database of a MySQL instance running on the localhost, listening on the port 3306, using the supervisor account whose password is ^%VM7H1]q":

const { Sequelize } = require('sequelize');

const database = new Sequelize('learn_backend', 'supervisor', '^%VM7H1]q"', {
  host: 'localhost',
  port: 3306,
  dialect: 'mysql',
});

Test the database connection

To test whether the connection to the database is successful, you can then use the asynchronous authenticate() method of the database handler:

try {
  await database.authenticate();
} catch(error) {
  //
}

Close the database connection

By default, Sequelize will keep the connection open and use it for all queries. If you need to close the database connection, you can use the asynchronous close() method of the database handler:

try {
  await database.close();
} catch(error) {
  //
}

Note: Once the database connection is closed, you will need to create a new Sequelize instance to open a new one.

🗒️ Summary

Here's a summary of what you've learned in this lesson:

  • The Sequelize class is used to instantiate a new database connection handler.
  • The authenticate() method is used to test the database connection.
  • The close() method is used to close the database connection.