MySQL with Node.js
Using MySQL with Node.js & the node-mysql JavaScript Client
Installing node-mysql
node-mysql can be installed via npm. We can get up and running like so:
cd sp-node-mysql
npm install mysql
Once you are done installing node-mysql module, you are good to go. For this demo I’ll be using a database called sitepoint and a table called employees. Here’s a dump of the database, so that you can get up and running quickly, if you wish to follow along:
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(50),
location varchar(50),
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
INSERT INTO employees (id, name, location) VALUES
(1, 'Jasmine', 'Australia'),
(2, 'Jay', 'India'),
(3, 'Jim', 'Germany'),
(4, 'Lesley', 'Scotland');
app.js
var mysql = require("mysql");
// First you need to create a connection to the db
var con = mysql.createConnection({
host: "localhost",
user: "jay",
password: "jay"
});
con.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
con.end(function(err) {
// The connection is terminated gracefully
// Ensures all previously enqueued queries are still
// before sending a COM_QUIT packet to the MySQL server.
});
Now open up a terminal and enter node app.js. Once the connection is successfully established you should be able to see the “Connection established” message in the console. If something goes wrong (for example you enter the wrong password), a callback is fired, which is passed an instance of the JavaScript Error object (err). Try logging this to the console to see what additional useful information it contains.
If JavaScript task runners are your thing, you can watch the file app.js for changes and have the task runner execute it every time a change is detected. Here’s how you might do that with Grunt.
package.json
"name": "sp-node-mysql",
"version": "0.1.0",
"devDependencies": {
"grunt": "~0.4.5",
"grunt-contrib-watch": "^0.6.1",
"grunt-execute": "^0.2.2",
}
}
Gruntfile.js
grunt.initConfig({
execute: {
target: {
src: ['app.js']
}
},
watch: {
scripts: {
files: ['app.js'],
tasks: ['execute'],
},
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-execute');
};
Executing Queries
host: "localhost",
user: "jay",
password: "jay",
database: "sitepoint"
});
if(err) throw err;
console.log('Data received from Db:\n');
console.log(rows);
});
{ id: 2, name: 'Jay', location: 'India' },
{ id: 3, name: 'Jim', location: 'Germany' },
{ id: 4, name: 'Lesley', location: 'Scotland' } ]
console.log(rows[i].name);
};
Creating
con.query('INSERT INTO employees SET ?', employee, function(err,res){
if(err) throw err;
console.log('Last insert ID:', res.insertId);
});
Updating
'UPDATE employees SET location = ? Where ID = ?',
["South Africa", 5],
function (err, result) {
if (err) throw err;
console.log('Changed ' + result.changedRows + ' rows');
}
);
Destroying
'DELETE FROM employees WHERE id = ?',
[5],
function (err, result) {
if (err) throw err;
console.log('Deleted ' + result.affectedRows + ' rows');
}
);