{"id":88172,"date":"2023-09-04T19:00:36","date_gmt":"2023-09-04T13:30:36","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=88172"},"modified":"2023-09-04T19:00:36","modified_gmt":"2023-09-04T13:30:36","slug":"node-js-mysql","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/node-js-mysql\/","title":{"rendered":"Node.js MySQL"},"content":{"rendered":"<h2>Node.js with MySQL<\/h2>\n<p>When it comes to working with databases, MySQL is one of the most widely used relational database management systems. In this article, we will explore how to create a Node.js application that connects to a MySQL database, perform CRUD operations, and handle errors effectively. We will cover all the necessary topics and provide code examples along the way.<\/p>\n<h3>Setting Up the Environment:<\/h3>\n<p>Before we begin, ensure that you have Node.js and MySQL installed on your machine. You can download Node.js from the official website (https:\/\/nodejs.org) and MySQL from the MySQL Downloads page (https:\/\/dev.mysql.com\/downloads\/). Once installed, you&#8217;re ready to proceed.<\/p>\n<h4>Initializing the Project<\/h4>\n<p>To create a Node.js project, open a terminal or command prompt, navigate to your desired directory, and run the following command:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">mkdir node-mysql-app\ncd node-mysql-app\nnpm init \u2013y\n<\/pre>\n<p>This will create a new directory called \u2018node-mysql-app&#8217; and generate a \u2018package.json\u2019 file that tracks your project&#8217;s dependencies.<\/p>\n<h4>Installing Dependencies<\/h4>\n<p>Next, we need to install the required dependencies: \u2018mysql\u2019 and \u2018dotenv\u2019. The \u2018mysql\u2019 package allows us to interact with the MySQL database, while \u2018dotenv\u2019 helps manage environment variables. Run the following command to install them:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">npm install mysql dotenv\n<\/pre>\n<h3>Creating a MySQL Database<\/h3>\n<p>Open your MySQL client and create a new database for our application. You can use the following SQL query:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">CREATE DATABASE node_mysql_app;\n<\/pre>\n<p><strong>The output will be:<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/MySQL-Database-output.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-88320\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/MySQL-Database-output.webp\" alt=\"MySQL Database output\" width=\"499\" height=\"153\" \/><\/a><\/p>\n<h3>Establishing a Connection<\/h3>\n<p>Now, let&#8217;s create a file called \u2018db.js\u2019 to handle the database connection. <strong>Add the following code to the file:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const mysql = require('mysql');\n \nconst connection = mysql.createConnection({\n  host: process.env.DB_HOST,\n  user: process.env.DB_USER,\n  password: process.env.DB_PASSWORD,\n  database: process.env.DB_NAME,\n});\n \nconnection.connect((error) =&gt; {\n  if (error) {\n    console.error('Error connecting to the database:', error);\n  } else {\n    console.log('Connected to the database!');\n  }\n});\n \nmodule.exports = connection;\n<\/pre>\n<p>This code imports the \u2018mysql\u2019 package and establishes a connection to the MySQL database using the provided credentials. It also exports the connection for other modules to use.<\/p>\n<p><strong>The output will be:<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/Establishing-a-Connection-.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-88321\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/Establishing-a-Connection-.webp\" alt=\"Establishing a Connection\" width=\"494\" height=\"71\" \/><\/a><\/p>\n<p><strong>In case of any error, It will give:<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/Establishing-a-Connection-output.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-88322\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/Establishing-a-Connection-output.webp\" alt=\"Establishing Connection output\" width=\"630\" height=\"66\" \/><\/a><\/p>\n<h3>Handling Environment Variables<\/h3>\n<p><strong>Create a \u2018.env\u2019 file in the root directory of your project and add the following lines:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">DB_HOST=localhost\nDB_USER=root\nDB_PASSWORD=your_password\nDB_NAME=node_mysql_app\n<\/pre>\n<p>Replace \u2018your_password\u2019 with your MySQL password. These environment variables will be used to configure the database connection.<\/p>\n<h3>Performing CRUD Operations<\/h3>\n<p>Now that we have established a database connection, let&#8217;s perform CRUD operations on a sample table called \u2018users\u2019.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const db = require('.\/db');\n \n\/\/ Create a new user\nconst newUser = { name: 'John Doe', email: 'johndoe@example.com' };\ndb.query('INSERT INTO users SET ?', newUser, (error, results) =&gt; {\n  if (error) {\n    console.error('Error creating a new user:', error);\n  } else {\n    console.log('New user created:', results.insertId);\n  }\n});\n \n\/\/ Read all users\ndb.query('SELECT * FROM users', (error, results) =&gt; {\n  if (error) {\n    console.error('Error retrieving users:', error);\n  } else {\n    console.log('Users:', results);\n  }\n});\n \n\/\/ Update a user\nconst userId = 1;\nconst updatedEmail = 'newemail@example.com';\ndb.query('UPDATE users SET email = ? WHERE id = ?', [updatedEmail, userId], (error, results) =&gt; {\n  if (error) {\n    console.error('Error updating user:', error);\n  } else {\n    console.log('User updated:', results.affectedRows);\n  }\n});\n \n\/\/ Delete a user\nconst userIdToDelete = 2;\ndb.query('DELETE FROM users WHERE id = ?', userIdToDelete, (error, results) =&gt; {\n  if (error) {\n    console.error('Error deleting user:', error);\n  } else {\n    console.log('User deleted:', results.affectedRows);\n  }\n});\n<\/pre>\n<p>In this example, we perform four operations: creating a new user, reading all users, updating a user&#8217;s email, and deleting a user. The db.query method executes SQL queries and provides the results or errors in the callback function.<\/p>\n<p><strong>The outputs will be:<\/strong><\/p>\n<p><strong>When creating a new user-<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/creating-output.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-88323\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/creating-output.webp\" alt=\"creating output\" width=\"443\" height=\"63\" \/><\/a><\/p>\n<p><strong>When reading all users-<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/reading-output.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-88324\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/reading-output.webp\" alt=\"reading output\" width=\"308\" height=\"67\" \/><\/a><\/p>\n<p><strong>When updating a user-<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/updating-output.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-88325\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/updating-output.webp\" alt=\"updating output\" width=\"292\" height=\"59\" \/><\/a><\/p>\n<p><strong>When deleting a user-<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/deleting-output.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-88326 size-full\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/deleting-output.webp\" alt=\"deleting output\" width=\"241\" height=\"57\" \/><\/a><\/p>\n<h3>Handling Errors<\/h3>\n<p><strong>To handle errors in a more organized manner, create an errorHandler.js file and add the following code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">function handleDatabaseError(error) {\n  console.error('Database error:', error);\n  \/\/ Handle the error according to your application's needs\n}\n \nmodule.exports = {\n  handleDatabaseError,\n};\n<\/pre>\n<p>You can call the \u2018handleDatabaseError\u2019 function whenever an error occurs in the database-related code.<\/p>\n<h3>Why Connect Node.js With MySQL?<\/h3>\n<p><strong>Numerous factors more than support integrating Node.js with MySQL for data storage, including:<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/Connect-Node.js-With-MySQL-1.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-88328 size-full\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/Connect-Node.js-With-MySQL-1.webp\" alt=\"Connect Node.js With MySQL \" width=\"640\" height=\"771\" \/><\/a><\/p>\n<h3>Quick Guide: Using MySQL in Node<\/h3>\n<p><strong>STEP-1:<\/strong> Make a fresh Node.js project.<\/p>\n<p>Using the NPM, start a new directory and a Node project.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">$ mkdir mysqlexperiment &amp;&amp; cd mysqlexperiment\n$ npm init --y\n<\/pre>\n<p><strong>STEP-2:<\/strong> Install The MySql Node Module<\/p>\n<p>Installing the mysql module from NPM<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">npm install --save mysql\n<\/pre>\n<p><strong>STEP-3:<\/strong> Connect With MySQL<\/p>\n<p>Copy and paste the following code into an app.js file. Adapt the MySQL login information to your system.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const mysql = require('mysql');\nconst connection = mysql.createConnection({\n    host: 'localhost',\n    user: 'user',\n    password: 'password',\n    database: 'databasename'\n});\n \nconnection.connect((err) =&gt; {\n    if (err) throw err;\n    console.log('Connected to MySQL Server!');\n});\n<\/pre>\n<p>Run the code using the following command.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">node app.js\n<\/pre>\n<p>Keep an eye on the terminal&#8217;s &#8216;Connected to MySQL Server!&#8217; message.<\/p>\n<p>If you have the most recent version of MySQL installed, you can receive the following problem.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">{\n code: 'ER_NOT_SUPPORTED_AUTH_MODE',\n errno: 1251,\n sqlMessage: 'Client does not support authentication protocol requested by server; consider upgrading MySQL client',\n sqlState: '08004',\n fatal: true\n}\n\n<\/pre>\n<p>Create a new user with the&#8217;mysql_native_password&#8217; authentication mechanism on your MySQL server to solve this problem.<\/p>\n<p>Here is an easy method for doing it. Start by entering the MySQL server as root.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">mysql -u root -p\n<\/pre>\n<p>Run each of these commands one at a time.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">CREATE USER 'newuser'@'localhost' IDENTIFIED WITH 'mysql_native_password' BY 'newpassword';\nGRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';\nFLUSH PRIVILEGES;\n<\/pre>\n<p>Pass the updated credentials to connect to the MySQL server in the code. Let&#8217;s continue now.<\/p>\n<h3>Pooling MySQL Connections<\/h3>\n<p>The earlier-demonstrated code is not intended for use in production. It serves only as a starting point for Node and MySQL. To increase MySQL&#8217;s performance in a production environment and prevent the MySQL server from becoming overloaded with connections, connection pooling must be used.<\/p>\n<p>Let&#8217;s use a clear example to demonstrate.<\/p>\n<p>Take a look at the code below.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const express = require(\"express\");\nconst app = express();\nconst mysql = require('mysql');\n \nconst connection = mysql.createConnection({\n    host: 'localhost',\n    user: 'username',\n    password: 'password',\n    database: 'databasename'\n});\n \nconnection.connect((err) =&gt; {\n    if (err) throw err;\n    console.log('Connected to MySQL Server!');\n});\n \napp.get(\"\/\", (req, res) =&gt; {\n    connection.query('SELECT * from users LIMIT 1', (err, rows) =&gt; {\n        if (err) throw err;\n        console.log('The data from users table are: \\n', rows);\n        connection.end();\n    });\n});\n \napp.listen(3000, () =&gt; {\n    console.log('Server is running at port 3000');\n});\n<\/pre>\n<p>In order to develop a web server, we are integrating the express module. Use the next command to install the module.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">npm install --save express\n<\/pre>\n<p>Every time a user request comes in, a MySQL connection is established. As soon as the MySQL server receives several concurrent requests, it becomes overloaded and fails.<\/p>\n<p>We will use a programme called Siege to model the concurrent connection scenario.<\/p>\n<p>To install it on an Ubuntu machine, use this command.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">sudo apt-get install siege\n<\/pre>\n<p>Run our Node server.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">node app.js\n<\/pre>\n<p>Let&#8217;s practise the simultaneous requests.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">siege -c10 -t1M http:\/\/localhost:3000\n<\/pre>\n<p>Assuming running on Node server Port 3000.<\/p>\n<p><strong>OUTPUT:<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/Node.js-MySQL-output.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-88329\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/Node.js-MySQL-output.webp\" alt=\"Node.js MySQL output\" width=\"1115\" height=\"584\" \/><\/a><\/p>\n<p>The information above shows that our server crashed while dealing with several concurrent requests. We apply the Pooling method to deal with this issue.<\/p>\n<p>In order to support connection pooling, let&#8217;s update our code.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const express = require(\"express\");\nconst app = express();\nconst mysql = require('mysql');\n \nconst pool = mysql.createPool({\n    host: 'localhost',\n    user: 'username',\n    password: 'password',\n    database: 'databasename'\n});\n \napp.get(\"\/\", (req, res) =&gt; {\n    pool.getConnection((err, connection) =&gt; {\n        if (err) throw err;\n        console.log('connected as id ' + connection.threadId);\n        connection.query('SELECT * from users LIMIT 1', (err, rows) =&gt; {\n            connection.release(); \/\/ return the connection to pool\n            if (err) throw err;\n            console.log('The data from users table are: \\n', rows);\n        });\n    });\n});\n \napp.listen(3000, () =&gt; {\n    console.log('Server is running at port 3000');\n});\n<\/pre>\n<p>Run the code using the following command.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">node app.js\n<\/pre>\n<p>Use this command to start ten simultaneous users of the siege for 1 minute.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">siege -c10 -t1M http:\/\/localhost:3000\n<\/pre>\n<p><strong>OUTPUT:<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/output-Node.js-MySQL.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-88330\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/output-Node.js-MySQL.webp\" alt=\"output Node.js MySQL\" width=\"1062\" height=\"581\" \/><\/a><\/p>\n<p>Multiple requests are being successfully handled by our server with ease. This strategy works like a charm in the production software solutions I&#8217;ve used, which have huge payloads.<\/p>\n<h3>Executing Queries<\/h3>\n<h4>1. Inserting data into Table<\/h4>\n<p>The code to add new rows to the table is provided here.<\/p>\n<p><strong>THE CODE:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const mysql = require('mysql');\n \nconst pool = mysql.createPool({\n    connectionLimit: 100, \/\/important\n    host: 'localhost',\n    user: 'root',\n    password: '',\n    database: 'todolist',\n    debug: false\n});\n \n\/\/ add rows in the table\n \nfunction addRow(data) {\n    let insertQuery = 'INSERT INTO ?? (??,??) VALUES (?,?)';\n    let query = mysql.format(insertQuery, [\"todo\", \"user\", \"notes\", data.user, data.value]);\n    pool.query(query, (err, response) =&gt; {\n        if (err) {\n            console.error(err);\n            return;\n        }\n        \/\/ rows added\n        console.log(response.insertId);\n    });\n}\n \n\/\/ timeout just to avoid firing query before connection happens\n \nsetTimeout(() =&gt; {\n    \/\/ call the function\n    addRow({\n        \"user\": \"Shahid\",\n        \"value\": \"Just adding a note\"\n    });\n}, 5000);\n<\/pre>\n<p>The query escape will be carried out by the mysql.format function.<\/p>\n<h4>2. Selecting data in Table<\/h4>\n<p><strong>THE CODE:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const mysql = require('mysql');\n \nconst pool = mysql.createPool({\n    connectionLimit: 100, \/\/important\n    host: 'localhost',\n    user: 'root',\n    password: '',\n    database: 'todolist',\n    debug: false\n});\n \n\/\/ query rows in the table\n \nfunction queryRow(userName) {\n    let selectQuery = 'SELECT * FROM ?? WHERE ?? = ?';\n    let query = mysql.format(selectQuery, [\"todo\", \"user\", userName]);\n    \/\/ query = SELECT * FROM `todo` where `user` = 'shahid'\n    pool.query(query, (err, data) =&gt; {\n        if (err) {\n            console.error(err);\n            return;\n        }\n        \/\/ rows fetch\n        console.log(data);\n    });\n}\n \n\/\/ timeout just to avoid firing query before connection happens\n \nsetTimeout(() =&gt; {\n    \/\/ call the function\n    \/\/ select rows\n    queryRow('shahid');\n}, 5000);\n<\/pre>\n<p>You can supply an array as the values if you want to add numerous rows to a single query. as in this.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">let insertQuery = 'INSERT INTO ?? (??,??) VALUES (?,?);\nlet values = [[\"shahid\",\"hello\"],[\"Rohit\",\"Hi\"]]; \/\/ each array is one row\nlet query = mysql.format(insertQuery,[\"todo\",\"user\",\"notes\",values]);\n<\/pre>\n<h4>3. Updating data in Table<\/h4>\n<p><strong>THE CODE:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const mysql = require('mysql');\n \nconst pool = mysql.createPool({\n    connectionLimit: 100, \/\/important\n    host: 'localhost',\n    user: 'root',\n    password: '',\n    database: 'todolist',\n    debug: false\n});\n \n\/\/ update rows\n \nfunction updateRow(data) {\n    let updateQuery = \"UPDATE ?? SET ?? = ? WHERE ?? = ?\";\n    let query = mysql.format(updateQuery, [\"todo\", \"notes\", data.value, \"user\", data.user]);\n    \/\/ query = UPDATE `todo` SET `notes`='Hello' WHERE `name`='shahid'\n    pool.query(query, (err, response) =&gt; {\n        if (err) {\n            console.error(err);\n            return;\n        }\n        \/\/ rows updated\n        console.log(response.affectedRows);\n    });\n}\n \n\/\/ timeout just to avoid firing query before connection happens\n \nsetTimeout(() =&gt; {\n    \/\/ call the function\n    \/\/ update row\n    updateRow({\n        \"user\": \"Shahid\",\n        \"value\": \"Just updating a note\"\n    });\n}, 5000);\n<\/pre>\n<h4>4. Deleting Rows in the table<\/h4>\n<p><strong>THE CODE:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const mysql = require('mysql');\n \nconst pool = mysql.createPool({\n    connectionLimit: 100, \/\/important\n    host: 'localhost',\n    user: 'root',\n    password: '',\n    database: 'todolist',\n    debug: false\n});\n \nfunction deleteRow(userName) {\n    let deleteQuery = \"DELETE from ?? where ?? = ?\";\n    let query = mysql.format(deleteQuery, [\"todo\", \"user\", userName]);\n    \/\/ query = DELETE from `todo` where `user`='shahid';\n    pool.query(query, (err, response) =&gt; {\n        if (err) {\n            console.error(err);\n            return;\n        }\n        \/\/ rows deleted\n        console.log(response.affectedRows);\n    });\n}\n \n\/\/ timeout just to avoid firing query before connection happens\n \nsetTimeout(() =&gt; {\n    \/\/ call the function\n    \/\/ delete row\n    deleteRow('shahid');\n}, 5000);\n<\/pre>\n<h3>Calling MySQL Stored Procedure Using Node<\/h3>\n<p>When a SQL query is run to retrieve data from the MySQL database, MySQL executes that query and returns the requested data. However, if our system needs to query the same data frequently, we would need to write multiple times to accomplish that. To address this issue, stored procedures were created. When a stored procedure is called, SQL statements that were previously stored in the MySQL server can be executed immediately.<\/p>\n<p>Additionally, Node.js allows you to directly invoke a stored process. If you don&#8217;t already have stored procedures in MySQL, you may perform the identical action by using the code below.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">CREATE PROCEDURE `getAllTodo`()\nBEGIN\nSELECT * FROM todo;\nEND$$\n<\/pre>\n<p><strong>The Node.js code for calling this stored process looks like this:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const mysql = require('mysql');\n \nconst pool = mysql.createPool({\n    connectionLimit: 100, \/\/important\n    host: 'localhost',\n    user: 'root',\n    password: '',\n    database: 'todolist',\n    debug: false\n});\n \nfunction callSP(spName) {\n    let spQuery = 'CALL ??';\n    let query = mysql.format(spQuery, [spName]);\n    \/\/ CALL `getAllTodo`\n    pool.query(query, (err, result) =&gt; {\n        if (err) {\n            console.error(err);\n            return;\n        }\n        \/\/ rows from SP\n        console.log(result);\n    });\n}\n \n\/\/ timeout just to avoid firing query before connection happens\n \nsetTimeout(() =&gt; {\n    \/\/ call the function\n    \/\/ call sp\n    callSP('getAllTodo')\n}, 5000);\n<\/pre>\n<h3>Conclusion<\/h3>\n<p>We covered the process of creating a Node.js application that connects to a MySQL database, performs CRUD operations, and handles errors effectively. We explored how to set up the environment, establish a database connection, handle environment variables, and execute queries. By following these steps, you can build powerful and scalable applications using Node.js and MySQL. Remember to handle errors gracefully and adapt the code to meet your specific project requirements.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Node.js with MySQL When it comes to working with databases, MySQL is one of the most widely used relational database management systems. In this article, we will explore how to create a Node.js application&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":88174,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4984],"tags":[5155,5110,5156,5157],"class_list":["post-88172","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-node-js-tutorials","tag-mysql","tag-nodejs","tag-nodejs-mysql","tag-nodejs-tutorial"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Node.js MySQL - TechVidvan<\/title>\n<meta name=\"description\" content=\"We will explore how to create a Node.js application that connects to a MySQL database, perform CRUD operations, and handle errors effectively.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/node-js-mysql\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Node.js MySQL - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"We will explore how to create a Node.js application that connects to a MySQL database, perform CRUD operations, and handle errors effectively.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/node-js-mysql\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-09-04T13:30:36+00:00\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Node.js MySQL - TechVidvan","description":"We will explore how to create a Node.js application that connects to a MySQL database, perform CRUD operations, and handle errors effectively.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/node-js-mysql\/","og_locale":"en_US","og_type":"article","og_title":"Node.js MySQL - TechVidvan","og_description":"We will explore how to create a Node.js application that connects to a MySQL database, perform CRUD operations, and handle errors effectively.","og_url":"https:\/\/techvidvan.com\/tutorials\/node-js-mysql\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2023-09-04T13:30:36+00:00","author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/node-js-mysql\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/node-js-mysql\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Node.js MySQL","datePublished":"2023-09-04T13:30:36+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/node-js-mysql\/"},"wordCount":1121,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/node-js-mysql\/#primaryimage"},"thumbnailUrl":"","keywords":["MySQL","Nodejs","nodejs mysql","nodejs tutorial"],"articleSection":["Node Js Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/node-js-mysql\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/node-js-mysql\/","url":"https:\/\/techvidvan.com\/tutorials\/node-js-mysql\/","name":"Node.js MySQL - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/node-js-mysql\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/node-js-mysql\/#primaryimage"},"thumbnailUrl":"","datePublished":"2023-09-04T13:30:36+00:00","description":"We will explore how to create a Node.js application that connects to a MySQL database, perform CRUD operations, and handle errors effectively.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/node-js-mysql\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/node-js-mysql\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/node-js-mysql\/#primaryimage","url":"","contentUrl":""},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/node-js-mysql\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Node.js MySQL"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/88172","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=88172"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/88172\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=88172"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=88172"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=88172"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}