why i can't getting callback as a record? must as a field('id')
ss : https://prnt.sc/ju4xb2
result reading as data row[0] from DAO
how i getting data from record ex: '0001' ? please help thankful
DAO
var executeQuery = function(query,callback) {
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'testt'
});
connection.connect();
connection.query(query, function(err, rows, fields) {
if (err) throw err;
connection.end();
console.log("Here in Dao: " + rows[0].mobile_phone);
callback(rows[0].mobile_phone);
});
};
module.exports = {
executeQuery: executeQuery
};
Model
var DAO = require('../lib/database.js');
module.exports = {
getuser : function(id,callback){
var User = DAO.executeQuery("select mobile_phone from ms_customer WHERE id = " + id, function(mobile_phone){
// var json = JSON.stringify(User);
console.log("Return from Dao = " +User);
callback(mobile_phone);
});
}
}
Controller
test : function(req,res){
var customerModel = require('../model/customer');
customerModel.getuser('0001', function(mobile_phone){
console.log("return from model_user = " + mobile_phone);
});
},
i always got error = 'ER_BAD_FIELD_ERROR: Unknown column '0001' in 'where clause''
i think error at query statement, please try this.
getuser : function(id,callback){
var User = DAO.executeQuery("select mobile_phone from ms_customer WHERE id = '" + id + "';", function(mobile_phone){
// var json = JSON.stringify(User);
console.log("Return from Dao = " +User);
callback(mobile_phone);
});
}
}
Related
I am trying to implement a synchronous query in mysql with node.js, I tried several ways and did not succeed
I am new to node.js
I use express.js
connection.js
var mysql = require('mysql');
var connMySql = function() {
return mysql.createConnection({
host : 'localhost',
user : 'root',
password : '******',
database : 'ress'
});
}
module.exports = function() {
return connMySql;
}
DAO.js
function UserDAO(connection){
this._connection = connection();
}
UserDAO.prototype.createUser = function (user, callback){
var sql = "insert into... ";
this._connection.query(sql, function(err, result){
//console.log(result)
//console.log()
if (err){
callback(err,false )
}
if (result){
var newI = result.insertId
var sqlOther = "insert into ..... ";
this._connection.query(sql, function(err, result){
if (err){
callback(err,false )
}else if (result.length > 0){
callback(false, result.insertId)
}
});
}
});
}
I try implements await, async and Promisse(.then) but no success.
What I need to make calls synchronously and return insert id?
thanks
From mysql repo I see that you're missing connection.connect()
connection.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '******',
database : 'ress'
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
DAO _connection must be closed when it's done with it's job
UserDAO.prototype.createUser = function (user, callback){
var sql = "insert into... ";
this._connection.query(sql, function(err, result){
//console.log(result)
//console.log()
if (err){
callback(err,false )
this._connection.end();
}
if (result){
var newI = result.insertId
var sqlOther = "insert into ..... ";
this._connection.query(sql, function(err, result){
if (err){
callback(err,false )
} else if (result.length > 0){
callback(false, result.insertId)
}
this._connection.end();
});
}
});
}
my loopback custom query cannot give response after some time. below is my code.
var ds = tbljourney.dataSource;
ds.connector.query("select * from user where email='" + data.email + "'"
, function (err, user) {
user = user[0];
console.log("user", user);
if (err) {
console.log(err);
}
else if (user) {
}
});
some time it give a response but after 50 or 60 attemps its stuck
try to run your queries using the method below. Here's I'm connecting to an Oracle database. A lot of concat gets messy.
Model.remoteMethod(data,cb){
var app = require('../server');
var ds = app.datasources.newDatasource;
var sql = "SELECT * FROM TABLE WHERE SITE_ID=:param1 AND "+
"(DESTINATION=:param2 OR USERNAME=:param2 )";
var params = [param1, param2];
ds.connector.execute(sql, params, function(err, result){
if (err) console.error("error: " + err);
cb(err, result);
});
}
I just started with crossbar and nodejs. I have a PHP background. I know that mysql on nodejs is async so I added a callback but i can't get the callback to return a value to the register method from crossbar. What would be the correct way to handle this?
var autobahn = require('autobahn');
var mysql = require('mysql');
var q = require('q');
var connection = new autobahn.Connection({
url: 'ws://127.0.0.1:8080/ws',
realm: 'realm1'}
);
connection.onopen = function (session) {
function dologin (cb) {
var connection = mysql.createConnection({
host : 'localhost',
user : 'xxxxx',
password : 'xxxxx',
database : 'xxxxx'
});
connection.connect();
connection.query('SELECT * from users LIMIT 0,2', function(err, rows, fields) {
if (!err){
cb("Done");
}else{
cb('Error while performing Query. ');
}
});
}
function login (args) {
return dologin(function(response){
return "status: "+response;
});
}
session.register('com.cms.login', login).then(
function (reg) {
console.log("Login registered");
},
function (err) {
console.log("failed to register procedure: " + err);
}
);
};
connection.open();
I'm new to Node.js. I have a function 'getFromDb' that accesses a mysql database and returns a json file with some data. What if I have an array of query data and I want to call the same function through a for loop to get a json file for each element of the array?
var http = require('http');
http.createServer(function(req, res) {
console.log('Receving request...');
var callback = function(err, result) {
res.setHeader('Content-disposition', 'attachment; filename=' + queryData+ '.json');
res.writeHead(200, {
'Content-Type' : 'x-application/json'
});
console.log('json:', result);
res.end(result);
};
getFromDb(callback, queryData);}
).listen(9999);
function getFromDb(callback, queryData){
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'xxxx',
password : 'xxxx',
database : 'xxxx',
port: 3306
});
connection.connect();
var json = '';
var data = queryData + '%';
var query = 'SELECT * FROM TABLE WHERE POSTCODE LIKE "' + data + '"';
connection.query(query, function(err, results, fields) {
if (err)
return callback(err, null);
console.log('The query-result is: ', results);
// wrap result-set as json
json = JSON.stringify(results);
/***************
* Correction 2: Nest the callback correctly!
***************/
connection.end();
console.log('JSON-result:', json);
callback(null, json);
});
}
You could use the async library for node for this. That library has many functions that make asynchronous programming in NodeJS much easier. The "each" or "eachSeries" functions would work. "each" would make all the calls to mysql at once time, while "eachSeries" would wait for the previous call to finish. You could use that inside your getFromDB method for your array.
See:
https://github.com/caolan/async#each
var http = require('http'),
async = require('async');
http.createServer(function(req, res) {
console.log('Receving request...');
var callback = function(err, result) {
res.setHeader('Content-disposition', 'attachment; filename=' + queryData+ '.json');
res.writeHead(200, {
'Content-Type' : 'x-application/json'
});
console.log('json:', result);
res.end(result);
};
getFromDb(callback, queryData);}
).listen(9999);
function getFromDb(callback, queryData){
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'xxxx',
password : 'xxxx',
database : 'xxxx',
port: 3306
});
connection.connect();
var arrayOfQueryData = ["query1", "query2", "query3", "query4", "query5"];
var jsonResults = [];
async.each(arrayOfQueryData, function (queryData, cb) {
var data = queryData + '%';
var query = 'SELECT * FROM TABLE WHERE POSTCODE LIKE "' + data + '"';
connection.query(query, function(err, results, fields) {
if (err)
return cb(err);
console.log('The query-result is: ', results);
// wrap result-set as json
var json = JSON.stringify(results);
console.log('JSON-result:', json);
jsonResults.push(json);
cb();
});
}, function (err) {
connection.end();
// callbacks from getFromDb
if (err) {
callback(err);
}
else {
callback(null,jsonResults);
}
});
}
use async module. it is the best one. If u dont want to add new module try following;
var count = 0;
array.forEach(function(element) { //array of the data that is to be used to call mysql
++count; //increase counter for each service call
async.db.call(element, callback); //the async task
}
var data = [];
function callback(err, resp) {
--count;//subtract for each completion
data.push(resp)
if(count == 0) { //return data when all is complete
return data;
}
}
I would recommend the async module though. it is very good practice and useful.
I'm new in Node.js. Trying to populate json file with data from database. And I need help for setting the name of this json file. Here is the code:
var http = require('http');
http.createServer(function(req, res) {
console.log('Receving request...');
var callback = function(err, result) {
res.writeHead(200, {
'Content-Type' : 'x-application/json'
});
console.log('json:', result);
res.end(result);
};
connectToDb(callback, queryData);}
).listen(9999);
function connecToDb(callback, queryData){
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'xxxx',
password : 'xxxx',
database : 'xxxx',
port: 3306
});
connection.connect();
var json = '';
var data = queryData + '%';
var query = 'SELECT * FROM TABLE WHERE POSTCODE LIKE "' + data + '"';
connection.query(query, function(err, results, fields) {
if (err)
return callback(err, null);
console.log('The query-result is: ', results);
// wrap result-set as json
json = JSON.stringify(results);
/***************
* Correction 2: Nest the callback correctly!
***************/
connection.end();
console.log('JSON-result:', json);
callback(null, json);
});
}
I get file named as "download", what should I use to name it "myJson.json"?
Add a content-disposition header with the value "attachment; filename=" + filename
where filename is whatver you want the filename to be.