2. You have to install MySQL driver to access a MySQL database with
Node.js. Download MySQl module from npm.
To download and install the "mysql" module, open the Command Terminal
and execute the following:
Ex:-
Connection with MySQL
npm install mysql
3. Create a js file named "connection.js" having the following
code:
connection.js:-
Connection with MySQL
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost", //host address
user: "root", // username of mysql
password: "12345" //password of mysql
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
4. Now run a js file named "connection.js".
Now open the command terminal and use the following
command:
connection.js:-
Connection with MySQL
node connection.js
5. INSERT INTO statement is used to insert records in MySQL.
Insert Record
var insertquery = "insert into tbl_student(id,name,age)
values ?";
var values = [
[null, 'abc', 22],
[null, 'def', 55]
];
mysql.query(insertquery, [values], function(err,
result)
{
if (err) throw err;
console.log('Record inserted');
});
6. The UPDATE command is used to update records in the
table.
Update Record
var sql = "UPDATE tbl_student SET age = 25 WHERE id=1";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result.affectedRows + " record(s) updated");
});
7. The DELETE FROM command is used to delete records from
the table.
Delete Record
var sql = "DELETE FROM tbl_student WHERE name =
‘xyz’ ";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Number of records deleted: " +
result.affectedRows);
});
8. The SELECT command is used to retrieve data from the
table.
Select Record
var sql = "SELECT * from tbl_student";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
9. The DROP TABLE command is used to delete or drop a table.
Drop Table
var sql = "DROP TABLE tbl_student";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table deleted");
});
10. Session IV completed
Address: 403, Venus Benecia, Bodakdev,Ahmedabad –
380053
Reach us : reach@techforceinfotech.com
Contact no: +91 (79) 48904529