It can be done with code
Lets get in to code,npm install mysql
- Add the "mysql" module to application
var mysql = require("mysql");
- Creating a connection object for sql connection
var con = mysql.createConnection({ host: "localhost", user: "root", password: "", database: "tutorialtest" });
Note:here you should enter your details for the database such as host, user, password etc.
- Making the connection with previously created connection object
con.connect(function(err){ if(err){ console.log('Error connecting to Db'); return; } console.log('Connection established'); });
In the function the we pass to connect() function we can add things to happen in a successful or unsuccessful connection
- Creating SQL query
var queryString='SELECT * FROM tblstudents';
-
Passing SQL query and handling function to query() method
con.query(queryString,function(err,rows){ if(err) throw err; console.log('Data received from Db:\n'); console.log(rows); });
- End the connection
con.end();
var mysql = require("mysql"); //add mysql module
// create a connection object to the db
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "tutorialtest"
});
//connect to database using connection object
con.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
//make the SQL quey
var queryString='SELECT * FROM tblstudents';
//execute the query
con.query(queryString,function(err,rows){
if(err) throw err;
console.log('Data received from Db:\n');
console.log(rows);
});
//end the connection
con.end();
Please add a comment if you have some thing to add or something is not clear to you.
No comments:
Post a Comment