node.js mysql pool connection

1. Install mysql.

sudo npm install mysql

2. Import mysql.

var mysql = require('mysql');

3. Create the pool object.

var pool =  mysql.createPool({
host : 'localhost',
user : 'root',
password: '',
database: 'test'
});

4. Get a connection from the pool object and do a select query.

pool.getConnection(function(err, connection){    
  //run the query
  connection.query('select * from students',  function(err, rows){
  	if(err)	throw err;
  	else {
  		console.log(rows);
  	}
  });
  
  connection.release();//release the connection
});

5. All together in mysql_pool_connection.js

var mysql = require('mysql');
var pool =  mysql.createPool({
host : 'localhost',
user : 'root',
password: '',
database: 'test'
});

pool.getConnection(function(err, connection){    
  //run the query
  connection.query('select * from students',  function(err, rows){
  	if(err)	throw err;
  	else {
  		console.log(rows);
  	}
  });
  
  connection.release();//release the connection
});

6. Run mysql_pool_connection.js

node mysql_pool_connection.js

Search within Codexpedia

Custom Search

Search the entire web

Custom Search