Use mysql module available on npmjs repository to connect MySQL database and execute queries from Node.js application.
Install Node.js MySQL Driver
You must have MySQL module installed in your application. You can install it using the following command.
npm install mysql
Node.js Connect to MySQL
Create a JavaScript file in your application and edit it in your favorite text editor.
vim connect_mysql.js
Add the following content. Change the MySQL connection values as per your system setup.
1 2 3 4 5 6 7 8 9 10 11 12 | var mysql = require('mysql'); var dbconn = mysql.createConnection({ host: "localhost", port: "3306", user: "root", password: "secure_password" }); dbconn.connect(function(err) { if (err) throw err; console.log("Database connected successfully!"); }); |
Test Connection
Finally, execute the connect_mysql.js file using node. On successful connection, it will display message like below.
node connect_mysql.js