Insert query in nodejs - mysql

I want to insert the value in this way any help me out this code.
It doesn't work for me . Error occurred as unknown column 'Fname1' in field list
app.post('/insert',function (req,res){
var Fname1=req.body.fname;
var Passwor1=req.body.pwd;
var sql="insert into test(Fname,Passwor) values(Fname1,Passwor1)";
con.query(sql,function(err,rows){
if(err) throw err;
res.send("Value has been inserted");
})
})
I don't want to insert in this way.
var data = {
Fname:req.body.fname,
Passwor:req.body.pwd
};
con.query("insert into test set ?",[data], function (err,rows){
if(err) throw err;
res.send("Value has been inserted");
})

Try this as your sql emit the Fname1 and Passwor1 as variables;
app.post('/insert',function (req,res){
var Fname1=req.body.fname;
var Passwor1=req.body.pwd;
var sql= "insert into test(Fname,Passwor) values ('"+Fname1+"', '"+Passwor1+"')";
con.query(sql,function(err,rows){
if(err) throw err;
res.send("Value has been inserted");
})
})

Your query should be like the following:
"insert into test(Fname,Passwor) values ('"+Fname1+"', '"+Passwor1+"')"

Related

How to return the response of Node.js mysql query connection

I am new at Node.js and I want to find something from database by using select query.
Here is my code.
var address = socket.request.client._peername.address;
var ip_addrss = address.split("::ffff:");
let mine = ip_addrss[1];
var location = iplocation_find(mine);
connection.connect( function () {
// insert user data with IP, location --- has got a status.
let stranger = "";
var values = [];
if (mine == null){
mine = "local server";
}
values.push(mine);
values.push('location');
var sql = "INSERT INTO user_list (IP_address, location) VALUES (?)";
connection.query(sql, [values], function (err, res){
if (err) throw err;
});
// control chatting connection between users
connection.query("SELECT IP_address FROM user_list WHERE status = ? AND location = ?", [0, "location"], function (err, res){
if (err) throw err;
stranger = res[0].IP_address;
console.log(stranger);
});
var room_users = [];
room_users.push(mine);
room_users.push(stranger);
console.log(room_users);
connection.query("INSERT INTO chatting_status (IP_client_1, IP_client_2) VALUES (?)", [room_users], function (err, res){
if (err) throw err;
console.log('inserted');
});
});
Now the problem is "stranger". It is not working anymore. Just always null.
Please tell me how I can return value in mysql query statement.
on my console, shows this.
[ 'local server', '' ]
127.0.0.1
inserted
[ '192.168.1.100', '' ]
127.0.0.1
inserted
Above, 'local server' and '192.168.1.100' are values of mine. And also '127.0.0.1' is the value of stranger only in query. But out of query it is just null.
You are using asynchronous operations with your .connect() and .query() calls. To sequence code with asynchronous callbacks like this, you have to continue the flow of control inside the callback and then communicate back errors or result via a callback.
You could do that like this:
let address = socket.request.client._peername.address;
let ip_addrss = address.split("::ffff:");
let mine = ip_addrss[1];
let location = iplocation_find(mine);
function run(callback) {
connection.connect( function () {
// insert user data with IP, location --- has got a status.
let values = [];
if (mine == null){
mine = "local server";
}
values.push(mine);
values.push('location');
var sql = "INSERT INTO user_list (IP_address, location) VALUES (?)";
connection.query(sql, [values], function (err, res){
if (err) return callback(err);
// control chatting connection between users
connection.query("SELECT IP_address FROM user_list WHERE status = ? AND location = ?", [0, "location"], function (err, res){
if (err) return callback(err);
let stranger = res[0].IP_address;
console.log(stranger);
let room_users = [];
room_users.push(mine);
room_users.push(stranger);
console.log(room_users);
connection.query("INSERT INTO chatting_status (IP_client_1, IP_client_2) VALUES (?)", [room_users], function (err, res){
if (err) return callback(err);
console.log('inserted');
callback(null, {stranger: stranger, room_users: room_users});
});
});
});
});
}
run((err, result) => {
if (err) {
console.error(err);
} else {
console.log(result);
}
});
Personally, this continually nesting callback code is a drawback of writing sequenced asynchronous code with plain callbacks. I would prefer to use the promise interface to your database and write promise-based code using async/await which will allow you to write more linear looking code.

I want to add a variable into mysql in nodejs

I insert a record in the database like this
connection.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO xtable (x_date, x_time, x_text) VALUES ('2018-05-26', '23:00:00', 'blablabla')";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
connection.end();
});
});
The above works but lets say I do
var ytime = '19:00:00';
var ydate = '2018-05-29';
var ytext = 'blabla';
connection.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO xtable (x_date, x_time, x_text) VALUES (ydate, ytime, ytext)";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
connection.end();
});
});
How do I do that? this gives just errors my node is v8.10.0
The latter didn't work because the sql statement did not interpret your ydate,ytime,ytext as variables but as a part of string. If you want to separate the statement and your data, you should do like this:
var ytime = '19:00:00';
var ydate = '2018-05-29';
var ytext = 'blabla';
var sql = "INSERT INTO xtable (x_date, x_time, x_text) VALUES (?,?,?)";
connection.query(sql, [ydate,ytime, ytext], function(err,result) {
...
});
You just switch your data to use placeholder values, then add the data separately:
connection.query(
"INSERT INTO xtable (x_date, x_time, x_text) VALUES (?, ?, ?)",
[ ydate, ytime, ytext ],
function (err, result) {
// ...
}
}
One thing to note about Node and MySQL is there's tools like Sequelize that make this a lot easier. Anything that supports Promises and async/await is almost always less fuss than a series of nested callbacks.

node mysql sequential query execution

I am trying to fetch some results and do the further processing based on those results, but I can't proceed to work it sequentially,
var sql = query1;
con.query(sql, function (err, results) {
if (err) throw err;
// ids => 5,2,3,4
for (i = 0; i < results.length; i++) {
target_user = results[i].ID
var sql = "DELETE QUERY";
con.query(sql, function (err) {
if (err) throw err;
console.log(target_user)
var sql = "INSERT QUERY";
console.log(sql)
con.query(sql, function (err) {
if (err) throw err;
})
})
}
})
The above code runs asynchronously, What I expect is an output in a loop like this
// "DELETE QUERY";
//5
// "INSERT QUERY";
// "DELETE QUERY";
//2
// "INSERT QUERY";
and so on..
but what I get is
// "DELETE QUERY";
//5
// "DELETE QUERY";
//5 //not fetching the next array val
// "INSERT QUERY";
// "INSERT QUERY";
Any help is much appriciated.
EDIT
from answers I updated code like this
now the code looks like this
aysnc.forEach(results, function(elem, callback){
target_user = elem.id
console.log('out')
console.log(target_user)
con.query(sql, function (err) {
if (err) throw err;
console.log('in')
console.log(target_user)
})
})
A strange thing happened that output is
out
5
in
5
out
2
in
5 //when it is supposed to be 2
You can still use npm module async in a different way
const mysql = require('mysql');
const async = require('aynsc');
var db; //database variable
async.series([
//creates DB connection and connects
function(callback){
db = mysql.createConnection(DB_INFO); //DB_INFO is an Object with information on the BD to be connected
db.connect(function(err){
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
callback(); //goes to the next function
});
},
//performs the Query 1
function(callback){
db.query('QUERY1', function(){
callback(); //goes to the next function
});
},
//performs the Query 2 only after Query 1 is finished
function(callback){
db.query('QUERY2', function(){
db.end(); //closes connection
callback();
});
}
]);
You could use recursion to solve something like this. Keep calling function until there is no elements left in results
con.query(sql, function (err, results) {
if (err) throw err;
deleteAndInsertResults(results);
})
function deleteAndInsertResult(results)
{
target_user = results[0].ID
var sql = "DELETE QUERY";
con.query(sql, function (err) {
if (err) throw err;
console.log(target_user)
var sql = "INSERT QUERY";
console.log(sql)
con.query(sql, function (err) {
if (err) throw err;
results.shift();
if(results.length){
return deleteAndInsertResult(results);
}
})
})
}
In node.js FOR loop will be executed parallely, so use async module or PROMISE below is an example using async
var async = require('aynsc');
con.query(sql, function (err, results) {
if (err) throw err;
// ids => 5,2,3,4
async.forEach(results, function(elem, callback){
target_user = results[i].ID
var sql = "DELETE QUERY";
con.query(sql, function (err) {
if (err) throw err;
console.log(target_user)
var sql = "INSERT QUERY";
console.log(sql)
con.query(sql, function (err) {
if (err) throw err;
callback()
})
})
}, function(err){
//final callback once loop is done
});
})

Use node-mysql to execute additional queries from each result

I'm trying to get a node-mysql connection query to work in series with the result of the original query. After all the setup is done, this is the problematic part. It seems that the connection has already ended. How can I ensure that the query in processRow gets executed in tandem with the result of the original?
function processRow(row, callback){
connection.query('INSERT INTO other_table VALUES (?)', row.id, function(err, rows, fields) {
if (err) throw err;
});
callback();
}
var query = connection.query('SELECT id from tbl limit 2');
query
.on('error', function(err){
throw err;
})
.on('fields', function(fields){
})
.on('result', function(row){
processRow(row, function(){
connection.resume();
});
})
.on('end', function(){
//
});
connection.end();
https://github.com/felixge/node-mysql
function processRow(row, callback){
connection.query('INSERT INTO other_table VALUES (?)', row.id, function(err, rows, fields) {
if (err) throw err;
callback();//callback should go here
});
}
then you could end the connection:
query.on('result', function(row){
processRow(row, function(){
connection.end(); //maybe end the connection once insertion into the table is done
});
})
I think the issue with your code that you have to call connection.pause() before calling processRow()

Nodejs with Mysql Database Return value

I have the following code. I am relative new to nodejs &js
I want to get values in 1. log but i get undefined.
Only 2. log is outputed to the log.
I read nodeJS return value from callback and
https://github.com/felixge/node-mysql but there is no example about return value.
I donot know how to use return statement with the given example in node-mysql page.
exports.location_internal = function (req, res) {
var r = getExternalLocation(2);
// 1. log
console.log(r);
res.send( r);
}
var getExternalLocation = function (id) {
pool.getConnection(function(err, connection){
if(err) throw err;
var response = {};
connection.query( "select * from external_geo_units where geo_unit_id = "+id, function(err, rows){
if(err) throw err;
response.data= rows;
// 2. log
console.log(response);
return response;
});
connection.release();
});
};
It's asynchronous, so you have to pass in a callback to get the value when it's ready. Example:
exports.location_internal = function(req, res, next) {
getExternalLocation(2, function(err, rows) {
if (err)
return next(err);
console.log(rows);
res.send(rows);
});
};
function getExternalLocation(id, cb) {
pool.getConnection(function(err, conn) {
if (err)
return cb(err);
conn.query("select * from external_geo_units where geo_unit_id = ?",
[id],
function(err, rows) {
conn.release();
cb(err, rows);
});
});
}