I am currently trying to insert data into a specific table name that is saved to a variable but I keep on receiving a ER_PARSE_ERROR whenever I try executing it.
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Test' SET `date` = '201
9-05-07', `league` = '1', `matchup` = '1'' at line 1
Here my what the post request looks like
app.post('/addData', function(req, res) {
var id = req.body.id
var data = {
date: req.body.date,
league: req.body.league,
matchup: req.body.matchup,
}
con.query('INSERT INTO ? SET ?', [id, data], function(err, resp) {
if (err) throw err;
res.redirect('back');
});
});
It seems like from the error message, there are additional quotes around Test when passed into the query but when doing console.log(id), it just prints out Test without the quotes.
app.post('/addData', function (req, res) {
var data = {
id: req.body.id,
date: req.body.date,
league: req.body.league,
matchup: req.body.matchup,
};
con.query('INSERT INTO Test SET ?', data, function (err, resp) {
if (err) throw err;
res.redirect('back');
});
});
Can you try this?
// This is the best ES6 way you can try out make some changes in your date format.
app.post('/addData', async (req, res) => {
var data = {
id: req.body.id,
date: req.body.date,
league: req.body.league,
matchup: req.body.matchup,
};
await con.query('INSERT INTO Test SET ?', data, (err, resp) => {
if (err) throw err;
res.redirect('back');
});
});
Related
I'm trying to call a saved stored procedure from SQL in my node app. my server is connected and I am able to execute my selectRandom5 saved proc with no problems.
the issue I am having is when I try to do a getById where I need to declare the #Id input. I've tried a couple of variations of the function with no luck, here are two I've tried.
the error message I get with this is UnhandledPromiseRejectionWarning: RequestError: Incorrect syntax near '?'.
selectById(req, res) {
var theId = req.params.id;
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query("CALL Addresses_SelectById(?)", [theId], function (err, recordset) {
if (err) console.log("connect", err);
// send records as a response
res.send(recordset);
console.log(recordset);
});
});
}
and then there's this other function I've tried, and the error message I get from this is 'Must declare the scalar variable "#Id".'
selectById(req, res) {
var theId = req.params.id;
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query(`SET #Id = ${theId}CALL Addresses_SelectById(#Id)`, function (err, recordset) {
if (err) console.log("connect", err);
// send records as a response
res.send(recordset);
console.log(recordset);
});
});
}
I just want to be able to pass parameters to SQL to be able to create update or get by but so far I haven't been able to figure out the proper way to pass the parameters.
any help would be appreciated! thanks guys
I FOUND IT GUYS!
selectById(req, res) {
var theId = req.params.id;
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.input("Id", sql.Int, theId);
request.execute("Addresses_SelectById", function (err, recordset) {
if (err) console.log("connect", err);
// send records as a response
res.send(recordset);
console.log(recordset);
});
});
I changed it to this and it works
Problem 1:
Suggested alternate syntax:
selectById(req, res) {
var theId = req.params.id;
let sql = `CALL Addresses_SelectById(?)`;
connection.query(sql, theId, (error, results, fields) => {
if (error) {
return console.error(error.message);
}
console.log(results[0]);
// Possibly stringify "results" to JSON before sending...
res.send(results);
});
}
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'm implement a simple high score board with RESTful, the server uses NodeJS and MySQL. I get the problem when implement the PUT method while the others (GET, POST, DELETE...) work well in both client and POSTMAN as I expected.
In MySQL, I create a table with only 2 values are "username" and "score".
Here is my route code:
'use strict';
module.exports = function(app) {
let userCtrl = require('./controllers/UserControllers');
// routes
app.route('/users')
.get(userCtrl.get)
.post(userCtrl.store);
app.route('/users/:username')
.get(userCtrl.detail)
.put(userCtrl.update)
.delete(userCtrl.delete);
app.route('/leaderboard')
.get(userCtrl.top);
};
Here is my controller source code:
'use strict';
const util = require('util');
const mysql = require('mysql');
const db = require('./../db.js');
module.exports = {
get: (req, res) => {
let sql = 'SELECT * FROM leaderboard';
db.query(sql, (err, response) => {
if (err) throw err;
res.json(response);
});
},
store: (req, res) => {
let sql = 'INSERT INTO leaderboard SET ? ';
// sql = 'INSERT INTO leaderboard_log SET '
let data = req.body;
db.query(sql, [data], (err, response) => {
if (err) throw err;
res.json({message: 'Insert success!'});
});
},
// the 'update' here works well in POSTMAN
update: (req, res) => {
let sql = 'UPDATE leaderboard SET ? WHERE username = ?';
let data = req.body;
let username = req.params.username;
db.query(sql, [data, username], (err, response) => {
if (err) throw err;
res.json({message: 'Update success!'});
});
}
};
The client in javascript uses PUT method
function httpPut(theUrl, data, callbackSuccess, callbackError) {
$.ajax({
type: "PUT",
url: theUrl,
success: callbackSuccess,
error: callbackError,
dataType: "json",
crossDomain: true
});
}
// how to pass the params 'username, 'newScore' to httpPUT ?!?
function updateUser(username, newScore) {
let data = {};
data['username'] = username;
data['score'] = newScore;
httpPut(URL_PUT_USER + username, data, function(data) {
// success
console.log("success update");
}, function(data) {
// fail
console.log("update error");
});
}
The problem is the function
updateUser(username, newScore)
which I don' know how to pass the param so that the update: (req, res) will understand.
Note that I tested using POSTMAN to update the record and the update: (req, res) works well.
Any help is appreciate. Thank you!.
PS: here is the error on server:
simple_leaderboard\node_modules\mysql\lib\protocol\Parser.js:80
throw err; // Rethrow non-MySQL errors
^
PUT maps to store operation, where your sql is defined as :
let sql = 'INSERT INTO leaderboard SET ? ';
This is not a valid SQL insert statement.
You probably want :
let sql = 'INSERT INTO leaderboard(username, data) VALUES(?, ?)';
let username = req.params.username;
let data = req.body;
db.query(sql, [username, data], ...
I've been using mountebank to do some stubbing for performance testing and its an awesome tool. The functional teams have asked if it can be repurposed to support functional testing and I'd said i'd have a look.
What I want to achieve is to select from a mysql database an account number and its account balance and then return the balance to the client (in this case a jmeter harness)
function (request, state, logger) {
logger.info('GBG - getAccountBalance');
var mysql = require('mysql');
var result = '';
var con = mysql.createConnection({
host: "localhost",
user: "user",
password: "password",
database: "customer"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
con.query('select * from accounts', function (err, rows, fields) {
if (err) throw err;
console.log(rows);
console.log('accountNumber is : ', rows[0].accountNumber);
result = rows[0].accountNumber;
});
console.log('result is : ', result);
var response = result;
return {
headers: {
'Content-Type': 'application/xml',
'Connection': 'Keep-Alive'
},
body: response
};
}
The result of the console log is:
result is :
Connected!
[ RowDataPacket { accountNumber: 777777, accountBalance: 777 } ]
accountNumber is : 777777
Not sure what I'm doing wrong and why the result is : lines comes up first despite being later in the code.
Any advice appreciated.
Full disclosure, I've been using mountebank for about two weeks so I'm a real beginner.
The function keyword inside connect and query is called callbacks, and only executed after the function itself is done. so your code would look like:
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query('select * from accounts', function (err, rows, fields) {
if (err) throw err;
console.log(rows);
console.log('accountNumber is : ', rows[0].accountNumber);
result = rows[0].accountNumber;
console.log('result is : ', result);
var response = result;
});
});
and so on, but you just introduced callback hell to your code.
async is your friend.
EDIT:
following an example:
async.waterfall([
function (callback) {
//do some async function here
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
//call this when you are done
//you can even pass param to next function
callback(null,true);
});
},function (isConnected,callback1) {
if !(isConnected){
console.log("Connection failed! Skipping Query...")
callback1(null,"Error");
}
//do another async function here:
con.query('select * from accounts', function (err, rows, fields) {
if (err) throw err;
console.log(rows);
console.log('accountNumber is : ', rows[0].accountNumber);
result = rows[0].accountNumber;
callback1(null,"Complete");
});
}
], function (err,result) {
if(result == "Error"){
alert("Someting went wrong!");
}
if(result == "Complete"){
alert("Done!");
}
return 0;
});
note:I haven't written JS for awhile. Written this off of some existing code and haven't been tested. Also, Promise is also something that would help, but haven't looked into personally. BlueBird is a library for that.
The simplest way to get Data form mysql database using Promise and async await.
Get data dynamically by providing id to the SQL query.
With the help of following code snippet. First Your query will get execute fully the other process will execute.
response will be sent after execution of query is fully done. (sometimes response is sent first then execution of query completes)
async function getData(customerId){
let sql = `SELECT * FROM customer_info WHERE customerID = ${customerId}`
await connection.query(sql, (err, result) => {
data = {
CustomerId : result[0].customerID,
FirstName: result[0].FirstName,
LastName: result[0].LastName
}
})
}
function connectToDB(customerId){
return new Promise((resolve, reject) => {
getData(customerId).then(()=>resolve())
})
}
app.get('/customer/:id', (req, res) => {
let customerId = req.params.id
// Caller Function to all functions
async function callerFun(){
await connectToDB(customerId);
res.send("Execution Done");
}
callerFun();
})
I am new to nodejs and mysql. I want to insert some data to mysql database using nodejs. I've tried to do it with and without mysql-crud modules but I failed. Can anyone help me?
exports.insertquotereq = function(req, res){
var chat_data = {
to_country: req.whereto,
to_airport: req.toairport,
from_country: req.fromwhere,
from_airport: req.fromairport,
planetype: req.planetype,
startdate: req.startdate,
starttime: req.starttime,
returndate: req.returndate,
returntime: req.returndate,
email: req.email,
distance: req.distance,
estimatedhrs: req.estimatedhrs,
planecostperhr: req.planecostperhr,
estimatedcost: req.estimatedcost,
estimated_time: req.estimated_time
};
//console.log('chat_data',chat_data);
var insert = connection.query("INSERT INTO chat SET ?", chat_data, function(err, result){
if(err) throw err;
console.log('data inserted'+insert);
});
};