Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Node.js is a powerful and popular back-end runtime environment that executes JavaScript code. It is used for running JavaScript code outside of the client’s browser. MySQL is a free and open-source Relational Database that is currently developed by Oracle.
In this article, we will discuss how to use MySQL in Node.js and what are the steps to install, connect and run MySQL queries in Node.js.
To use MySQL from node.js the first thing we would need to do is to create a connection to MySQL. Create a .js file on your system and run the below code after changing the MySQL credentials according to your setup:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'admin',
password : 'password',
database : 'test'
});
connection.connect(function(error) {
if (error) throw error;
console.log('MySQL connection successfully established');
});
You can also try this code with Online Javascript Compiler
We first created a MySQL connection through which we will run all the queries. We did this with the help of the createConnection call in the MySQL npm module. After that using some predefined strings for creating a database, creating a table, and a few DML operations we used the query function in the MySQL module to first create a database and a table in it and then ran insert, update, delete and select on the table that we created.
Frequently Asked Questions
What is MySQL?
MySQL is a free and open-source relational database written in C/C++. It is currently the most popular open-source SQL database Management system which is maintained and developed by Oracle.
How can we use MySQL in Node.js?
To use MySQL in Node.js, we can install the already available module in the npm registry which is called by the name ‘mysql’. It has vast features and is easy to install directly through the npm install command.
What makes MySQL a good choice to be used with Node.js?
MySQL is a good database choice as It is easy to use, fast, and reliable. It is open source and thus free to use. MySQL is a secure database due to its solid data security layer that encrypts data and prevents data breaches. It has a large community and is widely adapted in the industry.
How can we run queries from the MySQL module in npm?
To run queries from the MySQL module in npm, we have to use the function query which takes the argument of the SQL command. It returns an error if there was any issue in the execution otherwise it returns the result of the query which can be used to analyze the data.
In this article, we learned how to use MySQL in Node.js. We also learnt how to create a database, create a table and run DML operations like insert, update, delete, and select on the create table.