A first database application
Once you are up and running, let's start with a first, simple database application. Create a file index.js
in the directory where you installed the mysql
module, and fill it with the following code:
'use strict'; var mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'root' }); connection.query( 'SELECT "foo" AS first_field, "bar" AS second_field', function (err, results, fields) { console.log(results); connection.end(); } );
Let's see what exactly happens here. First, we include the external mysql
library at var mysql = require('mysql'
line. We then create a new object dubbed connection
in the var connection = mysql.createConnection({
line.
This object is a representation of our connection with the database. No connection without connecting, which is why we call the createConnection
function with the parameters necessary to connect and authenticate against the database server: the...