node.js mysql single connection

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

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

3. Create mysql database connection.
[code language=”javascript”]
var connection = mysql.createConnection({
host : ‘localhost’,
user : ‘root’,
password: ”
});
connection.connect();
[/code]

4. Choose a database to work on.
[code language=”javascript”]
connection.query(‘use test’);
[/code]

5. Do a select against the students table in the database test.
[code language=”javascript”]
var myQuery = ‘select * from students’;
connection.query(myQuery, function(err, rows) {
if(err) throw (err);
else {
console.log( rows );
}
});
[/code]

6. Close the connection.
[code language=”javascript”]
connection.end(function(err){
if(err)throw(err);
else {
console.log(‘The database connection has been terminated.’);
}
});
[/code]

7. All together in a js file, nodejs_mysql_single_connection.js
[code language=”javascript”]
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.’);
}
});
[/code]

8. Run the program.
[code language=”shell”]
node nodejs_mysql_single_connection.js
[/code]

Search within Codexpedia

Custom Search

Search the entire web

Custom Search