Search code examples
mysqlnode.jsnode-mysql

How to make a connection with MySQL in NodeJS?


I am new to NodeJS application development.

My requirement is to store my registration form data in a MySQL database.

Before that, I want to know how to establish the connection with a MySQL database. After that, store the form data.


Solution

  • Well, I present to you NPM and the world of requiring packages. ;)

    NPM stands for Node Package Manager. It is where we can add public or private packages that extends Node functionalities.

    Take a look at the MySQLpackage for NodeJS .

    var mysql = require('mysql'); 
    var connection = mysql.createConnection(
      {   
        host     : 'localhost',   
        user     : 'me',  
        password : 'secret',   
        database : 'my_db' 
      });   
    
      connection.connect();  
    
      connection.query('SELECT 1 + 1 AS solution', 
        function(err, rows, fields) {   if (err) throw err;
          console.log('The solution is: ', rows[0].solution); 
        });   
    
      connection.end();
    

    With this, you can simply connect to your DB.