Using the Node MySQL driver

There is a popular MySQL driver available for Node.js which is a pure JavaScript implementation. If you want to use some other database, then use a suitable library for that database. Using this driver is very simple and straightforward. To query a database object, you simply create a connection to the database configuration and start hitting the query. A simple Node.js example to query the database is as follows:

const mysql = require('mysql'); 

const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password',
database : 'customer_manager' //your database name here
});

// Connect to the data base
connection.connect();

connection.query('SELECT * FROM customers, function(err, rows) {
if (err) throw err;
console.log(rows.length);
});

connection.end();

Creating the database connection is simple and can be done using the createConnection method with your database configuration as parameters. Once the connection object is ready, then you need to connect to the database using the connect method. Then you can start querying the database object using the query method, which will provide the result in the callback function. connection.end() will close the connection. But the recommended way to connect to the database is as follows:

const connection = mysql.createConnection({
// Your database config here
});
connection.connect(function(error) {
if(error) {
console.log(error);
return;
}
connection.query('SELECT * FROM Customers', function(err, rows) {
if(err) {
console.log(error);
return;
}
console.log(rows.length + ' record found');
});
});

A direct call to the connection.query will also establish the connection in an implicit way, and that can also work in our case.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.133.117