multiple queries in node js
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'yourusername',
password: 'yourpassword',
database: 'yourdatabase'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL database');
// First query
connection.query('SELECT * FROM users', (err, results) => {
if (err) throw err;
console.log('First query results:', results);
// Second query
connection.query('SELECT * FROM products', (err, results) => {
if (err) throw err;
console.log('Second query results:', results);
// Third query
connection.query('SELECT * FROM orders', (err, results) => {
if (err) throw err;
console.log('Third query results:', results);
// Close the connection
connection.end((err) => {
if (err) throw err;
console.log('MySQL connection closed');
});
});
});
});
});
Explanation:
1. Import MySQL Module: Require the mysql
module in your Node.js application to work with MySQL databases.
2. Create Connection: Create a connection to the MySQL database using the createConnection
method and provide necessary connection details like host, username, password, and database name.
3. Connect to Database: Use the connect
method to establish a connection to the MySQL database. Handle any connection errors that might occur.
4. First Query: Execute a SELECT * FROM users
query. Upon success, log the results to the console.
5. Second Query: Perform another query SELECT * FROM products
. Handle any errors and log the results.
6. Third Query: Execute a SELECT * FROM orders
query. Handle errors and log the results.
7. Close Connection: Use the end
method to gracefully close the MySQL connection. Handle any potential errors while closing the connection.
This code demonstrates how to perform multiple queries sequentially in Node.js using the mysql
module and handle each query's results and errors.