node.js mysql single connection

1. Install mysql module

sudo npm install mysql

2. Import mysql.

var mysql = require('mysql');

3. Create mysql database connection.

var connection =  mysql.createConnection({
  	host : 'localhost',
  	user : 'root',
  	password: ''
  });
connection.connect();

4. Choose a database to work on.

connection.query('use test');

5. Do a select against the students table in the database test.

var myQuery = 'select * from students';	
connection.query(myQuery, function(err, rows) {
	if(err) throw (err); 
	else {
		console.log( rows );
	}
});

6. Close the connection.

connection.end(function(err){
	if(err)throw(err);
	else {
		console.log('The database connection has been terminated.');
	}
});

7. All together in a js file, nodejs_mysql_single_connection.js

var mysql = require('mysql');

var connection =  mysql.createConnection({
  	host : 'localhost',
  	user : 'root',
  	password: ''
  });
connection.connect();

connection.query('use test');
var myQuery = 'select * from students';	
connection.query(myQuery, function(err, rows) {
	if(err) throw (err); 
	else {
		console.log( rows );
	}
});

connection.end(function(err){
	if(err)throw(err);
	else {
		console.log('The database connection has been terminated.');
	}
});

8. Run the program.

node nodejs_mysql_single_connection.js

Search within Codexpedia

Custom Search

Search the entire web

Custom Search