How to connect xampp mysql with node js

How to connect xampp mysql with node js

Hello Guys,

We can easily connect the Nodejs with xampp by follow simple steps -

Nodejs required a specfic port to run on system and defaluts port is 8080, So let's starts

  • Download Nodejs form its website ,If node is installed successfully then open terminal or Git  Bash to check 
    Run command : node -v and npm -v it gives node version ,If it shows then you installed the node successfully.
  • Install It whole package, After then make folder in any drive with any name let's I take node_code in c drive so my path is :
    c:/node_code
  • Now Install Xampp (If not installed )download.html, and run Apache , If no error on, then we are almost done.
  • Now create a .js file in node_code folder let name that first_node.js and the below code :
    var http = require('http');http.createServer(function (req,res){ res.write('Nodejs started using xampp'); res.end();}).listen(8080);
    console.log('http server started'); 
  • Now open Git Bash or Command prompt on which you run the node -v command and navigate to the node_code folder by cd command
  • Now use Command 
    node first_node.js
  • after run this command you will see  "http server started" appear on command prompt.
  • Now Open any browser you have run localhost:8080 you will appear a writemessage.
    "Nodejs started using xampp"
  • That it, Nodejs connected with Xampp. By using same concept you will connect your server to Nodejs and run Nodejs on your website.

Thanks

Comments

Add new comment

Node.js and MySQL are some of the necessary binding needed for any web application. MySQL is one of the most popular open-source databases in the world and efficient as well. Almost every popular programming language like Java and PHP provides drivers to access and perform operations with MySQL.

In this Node js and MySQL tutorial, we are going to learn how to connect Node js server with MySQL database. We will also learn how to pool connections to improve performance, query the tables, and call stored procedures.

To be able to follow up with the code examples in this Node.js and MySQL tutorial, you should have MySQL installed on your computer.

You can download a free MySQL database at https://www.mysql.com/downloads/.

Quick Start: How to Use MySQL in Node

Assuming you have Node and MySQL installed on your computer. Let’s quickly use MySQL in Node in three easy steps:

Step 1: Create a new Node.js project

Create a new directory and initialize a Node project using the NPM.

$ mkdir mysqlexperiment && cd mysqlexperiment
$ npm init --y

Step 2: Install mysql node module

Install the mysql node module using the NPM.

Step 3: Connect with MySQL

Create an app.js file and copy/paste the code shown below. Change the MySQL credentials accordingly with your system.

const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'user',
  password: 'password',
  database: 'databasename'
});

connection.connect((err) => {
  if (err) throw err;
  console.log('Connected to MySQL Server!');
});

Run the code using the following command.

Observe the ‘Connected to MySQL Server!’ message in the terminal.

If you have the latest MySQL server installed, you might end up getting an error saying the following.

{
  code: 'ER_NOT_SUPPORTED_AUTH_MODE',
  errno: 1251,
  sqlMessage: 'Client does not support authentication protocol requested by server; consider upgrading MySQL client',
  sqlState: '08004',
  fatal: true
}

To tackle this issue, create a new user in your MySQL server with ‘mysql_native_password’ authentication mechanisum.

Here is how you can do it quickly. First, log in to the MySQL server using root access.

Then run these commands one by one.

CREATE USER 'newuser'@'localhost' IDENTIFIED WITH 'mysql_native_password' BY 'newpassword';
GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';
FLUSH PRIVILEGES;

In the code, pass the new credentials to connect to the MySQL server. Let’s proceed further.

Pooling MySQL Connections

The code shown earlier is not meant for production use. It’s merely to get you started with Node and MySQL. In a production scenario, we must use connection pooling to improve the performance of MySQL and not overload the MySQL server with too many connections.

Let’s explain it with a simple example.

Consider the code shown below.

const express = require("express");
const app = express();
const mysql = require('mysql');

const connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'username',
  password : 'password',
  database : 'databasename'
});

connection.connect((err) => {
    if(err) throw err;
    console.log('Connected to MySQL Server!');
});

app.get("/",(req,res) => {
    connection.query('SELECT * from users LIMIT 1', (err, rows) => {
        if(err) throw err;
        console.log('The data from users table are: \n', rows);
        connection.end();
    });
});

app.listen(3000, () => {
    console.log('Server is running at port 3000');
});

We are integrating express module to create a web server. Install the module using the following command.

npm install --save express

We are creating a MySQL connection on every request coming from the user. Soon after getting multiple concurrent requests, the MySQL server will get overloaded and throw an error.

To simulate the concurrent connection scenario, we are going to use a tool called siege.

Use this command to install it in Ubuntu system.

sudo apt-get install siege

Run our Node server.

Let’s simulate the concurrent requests.

siege -c10 -t1M http://localhost:3000

Assuming you are running the Node server on Port 3000.

Here is the output.

How to connect xampp mysql with node js

As you can see from the output above, our server crashed while handling concurrent requests. To tackle this scenario, we use the Pooling mechanism.

Connection Pooling is a mechanism to maintain a cache of database connection so that the connection can be reused after releasing it.

Let’s rewrite our code to support connection pooling.

const express = require("express");
const app = express();
const mysql = require('mysql');

const pool = mysql.createPool({
  host     : 'localhost',
  user     : 'username',
  password : 'password',
  database : 'databasename'
});

app.get("/",(req,res) => {
    pool.getConnection((err, connection) => {
        if(err) throw err;
        console.log('connected as id ' + connection.threadId);
        connection.query('SELECT * from users LIMIT 1', (err, rows) => {
            connection.release(); // return the connection to pool
            if(err) throw err;
            console.log('The data from users table are: \n', rows);
        });
    });
});

app.listen(3000, () => {
    console.log('Server is running at port 3000');
});

Run the app using the following command.

Let’s fire up 10 concurrent users for 1 minute using siege by using this command.

siege -c10 -t1M http://localhost:3000

Here is the output.

How to connect xampp mysql with node js

Our server is effectively handling multiple requests with ease. I have used this approach in multiple production software solutions with heavy payload and it works like charm.

Let’s learn how to execute various MySQL queries using Node.

Executing Queries

Let’s learn how to execute queries using Node.js.

Inserting Rows into Table

Here is the code to add new rows to the table.

const mysql = require('mysql');

const pool = mysql.createPool({
    connectionLimit : 100, //important
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'todolist',
    debug    :  false
});

// add rows in the table

function addRow(data) {
    let insertQuery = 'INSERT INTO ?? (??,??) VALUES (?,?)';
    let query = mysql.format(insertQuery,["todo","user","notes",data.user,data.value]);
    pool.query(query,(err, response) => {
        if(err) {
            console.error(err);
            return;
        }
        // rows added
        console.log(response.insertId);
    });
}

// timeout just to avoid firing query before connection happens

setTimeout(() => {
    // call the function
    addRow({
        "user": "Shahid",
        "value": "Just adding a note"
    });
},5000);

The mysql.format function will perform the query escape.

Querying data in Table

Here is the code to query rows in the table.

const mysql = require('mysql');

const pool = mysql.createPool({
    connectionLimit : 100, //important
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'todolist',
    debug    :  false
});

// query rows in the table

function queryRow(userName) {
    let selectQuery = 'SELECT * FROM ?? WHERE ?? = ?';    
    let query = mysql.format(selectQuery,["todo","user", userName]);
    // query = SELECT * FROM `todo` where `user` = 'shahid'
    pool.query(query,(err, data) => {
        if(err) {
            console.error(err);
            return;
        }
        // rows fetch
        console.log(data);
    });
}

// timeout just to avoid firing query before connection happens

setTimeout(() => {
    // call the function
    // select rows
    queryRow('shahid');
},5000);

If you would like to add multiple rows in a single query, you can pass an array in the values. Like this.

let insertQuery = 'INSERT INTO ?? (??,??) VALUES (?,?)';
    let values = [["shahid","hello"],["Rohit","Hi"]]; // each array is one row
    let query = mysql.format(insertQuery,["todo","user","notes",values]);

Updating data in Table

Here is the code to update the data in the table.

const mysql = require('mysql');

const pool = mysql.createPool({
    connectionLimit : 100, //important
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'todolist',
    debug    :  false
});

// update rows

function updateRow(data) {
    let updateQuery = "UPDATE ?? SET ?? = ? WHERE ?? = ?";
    let query = mysql.format(updateQuery,["todo","notes",data.value,"user",data.user]);
    // query = UPDATE `todo` SET `notes`='Hello' WHERE `name`='shahid'
    pool.query(query,(err, response) => {
        if(err) {
            console.error(err);
            return;
        }
        // rows updated
        console.log(response.affectedRows);
    });
}

// timeout just to avoid firing query before connection happens

setTimeout(() => {
    // call the function
    // update row
    updateRow({
        "user": "Shahid",
        "value": "Just updating a note"
    });
},5000);

Deleting Rows in the table

Here is the code to delete a row from the table.

const mysql = require('mysql');

const pool = mysql.createPool({
    connectionLimit : 100, //important
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'todolist',
    debug    :  false
});

function deleteRow(userName) {
    let deleteQuery = "DELETE from ?? where ?? = ?";
    let query = mysql.format(deleteQuery, ["todo", "user", userName]);
    // query = DELETE from `todo` where `user`='shahid';
    pool.query(query,(err, response) => {
        if(err) {
            console.error(err);
            return;
        }
        // rows deleted
        console.log(response.affectedRows);
    });
}

// timeout just to avoid firing query before connection happens

setTimeout(() => {
    // call the function
    // delete row
    deleteRow('shahid');
},5000);

Calling MySQL Stored Procedure Using Node

You can also call a stored procedure using Node.js. If you don’t have stored procedures created in MySQL, you can refer to the code below to do the same.

DELIMITER $$

  CREATE PROCEDURE `getAllTodo`()
BEGIN
    SELECT * FROM todo;
END$$

  DELIMITER ;

Here is the code to call the stored procedure from the code.

const mysql = require('mysql');

const pool = mysql.createPool({
    connectionLimit : 100, //important
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'todolist',
    debug    :  false
});

function callSP(spName) {
    let spQuery = 'CALL ??';
    let query = mysql.format(spQuery,[spName]);
    // CALL `getAllTodo`
    pool.query(query,(err, result) => {
        if(err) {
            console.error(err);
            return;
        }
        // rows from SP
        console.log(result);
    });
}

// timeout just to avoid firing query before connection happens

setTimeout(() => {
    // call the function
    // call sp
    callSP('getAllTodo')
},5000);

Conclusion :

MySQL is one of the widely used database engines in the world and with Node it really works very well. Node MySQL pooling and event-based debugging are really powerful and easy to code.

Further reading:

  • Node-mysql Github
  • Pro MERN Stack: Full Stack Web App Development with Mongo, Express, React, and Node

Can I use XAMPP MySQL in node JS?

Run command : node -v and npm -v it gives node version ,If it shows then you installed the node successfully. Now Install Xampp (If not installed )download. html, and run Apache , If no error on, then we are almost done. after run this command you will see "http server started" appear on command prompt.

How do I connect to a node js in MySQL?

Install MySQL Driver.
C:\Users\Your Name>npm install mysql..
var mysql = require('mysql');.
Run "demo_db_connection.js" C:\Users\Your Name>node demo_db_connection.js..
Connected!.
con. connect(function(err) { if (err) throw err; console. log("Connected!" ); con. query(sql, function (err, result) { if (err) throw err;.

How connect MySQL to XAMPP?

Create MySQL Database at the Localhost Open your browser and go to localhost/PHPMyAdmin or click “Admin” in XAMPP UI. Now click Edit privileges and go to Change Admin password, type your password there and save it. Remember this password as it will be used to connect to your Database.

Can I use PHPMyAdmin with NodeJs?

To interoperate with MySQL (in our case, we are using Xampp which includes PHPMyAdmin) using Node. js, you'll need the following node package named mysql. Then you'll be able to require the mysql module. Note: this module is exception safe.