node.js mysql pool connection

1. Install mysql.
[code language=”shell”]
sudo npm install mysql
[/code]

2. Import mysql.
[code language=”javascript”]
var mysql = require(‘mysql’);
[/code]

3. Create the pool object.
[code language=”javascript”]
var pool = mysql.createPool({
host : ‘localhost’,
user : ‘root’,
password: ”,
database: ‘test’
});
[/code]

4. Get a connection from the pool object and do a select query.
[code language=”javascript”]
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
});
[/code]

5. All together in mysql_pool_connection.js
[code language=”javascript”]
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
});
[/code]

6. Run mysql_pool_connection.js
[code language=”javascript”]
node mysql_pool_connection.js
[/code]

Search within Codexpedia

Custom Search

Search the entire web

Custom Search