Step 1: Import Sequelize and Configure Database Connection
First, ensure that Sequelize and the corresponding database driver (e.g., for MySQL, the mysql2 package) have been installed. Then, create a Sequelize instance and configure the database connection.
javascriptconst { Sequelize } = require('sequelize'); // Create a Sequelize instance and connect to the database const sequelize = new Sequelize('database', 'username', 'password', { host: 'host', dialect: 'mysql' // Use the mysql dialect });
Step 2: Execute Queries Using sequelize.query()
The sequelize.query() method can be used to execute any SQL statement. You can use placeholders to prevent SQL injection.
javascriptasync function executeQueries() { try { // Execute the first query const users = await sequelize.query("SELECT * FROM `users` WHERE `age` > ?", { replacements: [18], type: Sequelize.QueryTypes.SELECT }); console.log(users); // Execute the second query const activeUsers = await sequelize.query("SELECT * FROM `users` WHERE `status` = ?", { replacements: ['active'], type: Sequelize.QueryTypes.SELECT }); console.log(activeUsers); } catch (error) { console.error('Error executing queries:', error); } } executeQueries();
Step 3: Handle Asynchronous Operations
Since sequelize.query() returns a Promise, you must use async/await or .then/.catch to manage asynchronous logic. In the example above, async/await ensures queries execute sequentially and correctly handle results or errors.
Practical Application Example
Consider a scenario where you need to retrieve lists of all adult users and all active users from the database. Using this approach, you can easily execute both queries and process results separately. This method is highly practical for tasks like report generation or user management systems.
By using this method, you can maintain code clarity and efficiency while leveraging Sequelize's security features—such as preventing SQL injection—to ensure application security.