Node.js can be used in database applications. One of the most popular databases is MySQL.
Install MySQL Driver
To access a MySQL database with Node.js, we need a MySQL driver.
Command to download and install the "mysql" module:
C:\Users\Your Name>npm install mysql
Now, we can use this module to manipulate the MySQL database using Node.js code.
var mysql = require('mysql');
Create Connection
Start by creating a connection to the database. Use the username and password from your MySQL database.
NodeMySQL_conn.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
Run "NodeMySQL_conn.js"
C:\Users\Your Name>node NodeMySQL_conn.js
Connected!
Now we can start querying the database using SQL statements.
Query a Database
Use SQL statements to read from (or write to) a MySQL database. This is also called "to query" the database.
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Result: " + result);
});
});
The query method takes a sql statement as a parameter and returns the result.