In this tutorial you will learn about the Nodejs MySql Connection and its application with practical example.
MySQL is one of the most popular open source database, and almost every popular programming language like PHP or Java provides driver to access and perform operations with MySQL.
In this tutorial we will try play with MySQL Database with Node.js.
Node.js MySql Connection
In order to be able experiment with MySQL Database, you must have MySQL installed on your computer. Node.js can be easily connected to MySQL Database using following steps –
Step 1:- Let’s create a project folder as “nodemysql “application and switch to that project directory.
1 2 |
$ mkdir nodemysql $ cd nodemysql |
Step 2:- Now, run the following command to create the package.json –
1 |
$ npm init |
Install MySQL Driver
Step 3:- In order to access a MySQL database with Node.js, you need to install MySQL driver. Let’s download and install the “mysql” module using the following command –
1 |
$ npm install mysql |
Connecting MySQL Database With Node.js
Step 4:- Let’s create a MySQL database with the name of your choice.
Step 5:- Now, create a node_mysql_conn.js file and put the following code in it –
1 2 3 4 5 6 7 8 9 10 11 12 13 |
//node_mysql_conn.js var mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'nodemysql' }); connection.connect((err) => { if (err) throw err; console.log('Connected!'); }); |
Replace with your host name, database name, username and password correspondingly.
Step 6:- Save the code and open the terminal again, and type the following command in order to run the file.
1 |
$ node node_mysql_conn.js |
you will see following output on terminal –