Friday, 3 February 2017

How to execute MySQL queries in node.js?

How to execute MySQL queries in node.js?

Question: How to install mysql in nodeJS?
npm install mysql



Question: How to update mysql in nodeJS?
npm update mysql



Question: How to include MySQL in nodeJS?
var mysql = require("mysql");



Question: How to connect to MySQL in nodeJS?
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "mydb"
});



Question: How to handle error while connecting to MySQL in nodeJS?
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "mydb"
});
con.connect(function(err) {
    if (err) {
        console.log('Error connecting to database');
        return;
    }
    console.log('Connection established Successfully');
});



Question: How to insert record in database with nodeJS?
var post = {
    'userID': "1",
    'userName': 'username',    
    'device': 'web',
    'stream_time': "0",
    'user_display_name': "arun kumar gupta",
    'user_photo': "hello"
};
var mysqlProfiler = con.query('INSERT INTO messages set ?', post, function(err, result) {});
console.log(mysqlProfiler.sql);



Question: How to print SQL query in nodejs?
var mysqlProfiler = con.query('INSERT INTO messages set ?', post, function(err, result) {});
console.log(mysqlProfiler.sql);



Question: How to insert record in database - Full Example?
var mysql = require("mysql");
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "mydb"
});
var post = {
    'userID': "1",
    'userName': 'username',    
    'device': 'web',
    'stream_time': "0",
    'user_display_name': "arun kumar gupta",
    'user_photo': "hello"
};
var mysqlProfiler = con.query('INSERT INTO messages set ?', post, function(err, result) {});
console.log(mysqlProfiler.sql); //print the query



Question: How to fetch all records in nodeJS?
var uid=1002;
 mysqlConn.query('SELECT * FROM `messages` WHERE id = '+uid , function (error, results, fields) {
    if (results != null && results.length > 0) {
        for each (var results in res) {
            console.log(res);
         }
    }
}



No comments :

Post a Comment