ER_PARSE_ERROR node.js and mysql issue (INSERT INTO) - javascript

I want to do a simple insert with Node.js while I am using socket.io with node.js and MySQL. Don't know why, but I am geting this error
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''markos'' at line 1
My code:
When I try this, I get the above error.
io.on("connection", function(socket){
console.log("a user is connected " + socket.id );
socket.on("question", function (question){
let sql = "INSERT INTO nodeJs (name) VALUES ?";
con.query(sql, question, function (err) {
if (err) throw err;
console.log("1 record inserted");
});
});
});
});
if I try this simple code, everything works fine:
io.on("connection", function(socket){
console.log("a user is connected " + socket.id );
socket.on("question", function (question){
let sql = "INSERT INTO nodeJs (name) VALUES ('John')";
con.query(sql, function (err) {
if (err) throw err;
console.log("1 record inserted");
});
});
});
});
The question parameter always has a string.

You're missing the parentheses around the values:
let sql = "INSERT INTO nodeJs (name) VALUES (?)";
// Here ------------------------------------^-^

Related

Faulty SQL query in JavaScript?

Before I start, I'm aware of the risks I'm taking by connecting to a database via JavaScript. The thing with this project is that it's going to be for a slightly different purpose, so I'm fine with using JavaScript.
document.getElementsByClassName("option")[0].onclick = function() {
event.preventDefault();
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "dbname"
});
con.connect(function(err) {
if (err) throw err;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var sql = 'SELECT * FROM accounts WHERE email = ' + mysql.escape(email) + ' AND password = ' + mysql.escape(password);
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
});
}
So, I had technically done this before with PHP. It's just that I'm now doing it with JavaScript. Yet, something is clearly wrong. As you can see, I want to see the result in the console. Yet, I'm left with this:
I can't say I'm an experienced programmer - the truth is, this is just some kind of practice project, I'm a student. So any kind of help would be appreciated!
You need to quote strings in SQL. You didn't put quotes around the email and password.
But it's better to use parameters rather than substituting variables into the SQL, even if you escape them.
var sql = 'SELECT * FROM accounts WHERE email = ? AND password = ?';
con.query(sql, [email, password], function (err, result) {
if (err) throw err;
console.log(result);
});

NodeJS Returning 'undefined' In MySQL Query Function

I have a function that queries SQL to get a string called Prefix.
function getPrefix(Guild) {
let query = "SELECT Prefix FROM Guilds WHERE GuildId=?";
Connection.query(query, [Guild.id], (err, result) => {
if (err) throw err;
return result[0].GuildPrefix;
});
};
Whenever I print the Prefix out (console.log(result[0].Prefix);), it logs it fine - however, whenever I return it and then attempt to call the function, it always returns undefined.
I am using Node JS Version 10.15.1 & I am using MariaDB Version 10.1.37 on the Raspbian stretch of Debian. Please comment if I have left any other information out. Thanks.
In Nodejs the functions related to mysql are always asynchronous which means they will either not return anything or will retuen undefined.
So the solution is to use a callback function.
Eg.
function getPrefix(Guild, callback) {
let query = "SELECT Prefix FROM Guilds WHERE GuildId=?";
Connection.query(query, [Guild.id], (err, result) => {
if (err){
callback(JSON.stringify(err));
};
callback(JSON.stringify(result));
});
};

Assignments done in pool.connect

What does it do?
In the documentation, I do not understand the answer.
I'm not using it correctly, I get a query error from the database
pool.connect(function (err, client, done) {
if (err) console.log("connect " + err.toString());
else
client.query('SELECT id, "idName", "idContact", "idExperience",
"idSkill", "dateAdded", "dateColloquy"' +
'FROM public."applicant ";', function (err, result) {
if (err) {
console.log("query " + err.toString());
}
else {
console.log(result.rows);
//module.exports.res = result.rows;
}
done();
});
});
Now there are many errors, the error you are getting from the database (sad that you don't share it with us) should be the "dateColloquy"FROM part. Now once you fixed that and inserted a space before FROM, you'll notice that all your fields are not included as data, but exactly as what you wrote - idName (literally the string), ... for every field but id the same.
Use backticks (```) (or nothing at all) for column names, not " nor '.
The next error you'll experience will be that you are trying to
module.exports.res = result.rows;
You can't export asynchronous retrieved data like that.

Node.js process cannot recover after MySQL turned off, then turn on

I am using Node.js with MySQL and restify.
I have the following code which is run as part of a REST API. It works fine.
server.get('/test', function (req, res, next) {
var query_string =
"SELECT DATE(date_transacted) AS transaction_date, " +
" MonthReports.tb AS MonthReports__tb " +
" FROM monthly_reports MonthReports " +
" WHERE ( date_transacted >= \'2015-01-00\' AND date_transacted <= \'2015-09-00\' ) ";
connection.query(
query_string
, function (err, rows, fields) {
if (err) throw err;
res.send(rows);
});
});
If I deliberately turn off the MySQL database and makes a REST API call which will run the query, I will get the error
Cannot enqueue Query after fatal error.
At this point, I turn on the MySQL database. The node.js process is unable to recover and the same error keeps appearing when I make a REST API call. The REST API server is dead.
What can be done to make the Node.js REST API server code recoverable?
I am assuming you are connecting globally inside your script.
One simple way would be to create a connection per request:
server.get('/test', function (req, res, next) {
var query_string =
"SELECT DATE(date_transacted) AS transaction_date, " +
" MonthReports.tb AS MonthReports__tb " +
" FROM monthly_reports MonthReports " +
" WHERE ( date_transacted >= \'2015-01-00\' AND date_transacted <= \'2015-09-00\' ) ";
var connection = getConnection(function connected(err) {
if (err) {
// error connecting to mysql! alert user
} else {
connection.query(
query_string
, function (err, rows, fields) {
if (err) throw err;
res.send(rows);
});
}
});
});
The above code is psuedo code as i'm not familiar with the node mysql library. This will allow each request to see if mysql is able to be connected to, at the expense of having a connection per web request.
Another strategy could be to check err when you issue a query, and if there is an error try to reestablish the global connection
server.get('/test', function (req, res, next) {
var query_string =
"SELECT DATE(date_transacted) AS transaction_date, " +
" MonthReports.tb AS MonthReports__tb " +
" FROM monthly_reports MonthReports " +
" WHERE ( date_transacted >= \'2015-01-00\' AND date_transacted <= \'2015-09-00\' ) ";
connection.query(
query_string
, function (err, rows, fields) {
if (err) {
// Try to reconnect here instead of throwing error and stopping node process, and reissue query
}
res.send(rows);
});
});
This website gives a complete answer. Credit goes to the writer of this article, not me.
https://www.exratione.com/2013/01/nodejs-connections-will-end-close-and-otherwise-blow-up/
/**
* #fileOverview A simple example module that exposes a getClient function.
*
* The client is replaced if it is disconnected.
*/
var mysql = require("mysql");
var client = mysql.createConnection({
host: "127.0.0.1",
database: "mydb",
user: "username",
password: "password"
});
/**
* Setup a client to automatically replace itself if it is disconnected.
*
* #param {Connection} client
* A MySQL connection instance.
*/
function replaceClientOnDisconnect(client) {
client.on("error", function (err) {
if (!err.fatal) {
return;
}
if (err.code !== "PROTOCOL_CONNECTION_LOST") {
throw err;
}
// client.config is actually a ConnectionConfig instance, not the original
// configuration. For most situations this is fine, but if you are doing
// something more advanced with your connection configuration, then
// you should check carefully as to whether this is actually going to do
// what you think it should do.
client = mysql.createConnection(client.config);
replaceClientOnDisconnect(client);
client.connect(function (error) {
if (error) {
// Well, we tried. The database has probably fallen over.
// That's fairly fatal for most applications, so we might as
// call it a day and go home.
//
// For a real application something more sophisticated is
// probably required here.
process.exit(1);
}
});
});
}
// And run this on every connection as soon as it is created.
replaceClientOnDisconnect(client);
/**
* Every operation requiring a client should call this function, and not
* hold on to the resulting client reference.
*
* #return {Connection}
*/
exports.getClient = function () {
return client;
};
This answer was extracted from another link nodejs mysql Error: Connection lost The server closed the connection
The extracted code;
var db_config = {
host: 'localhost',
user: 'root',
password: '',
database: 'example'
};
var connection;
function handleDisconnect() {
connection = mysql.createConnection(db_config); // Recreate the connection, since
// the old one cannot be reused.
connection.connect(function(err) { // The server is either down
if(err) { // or restarting (takes a while sometimes).
console.log('error when connecting to db:', err);
setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
} // to avoid a hot loop, and to allow our node script to
}); // process asynchronous requests in the meantime.
// If you're also serving http, display a 503 error.
connection.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
handleDisconnect(); // lost due to either server restart, or a
} else { // connnection idle timeout (the wait_timeout
throw err; // server variable configures this)
}
});
}
handleDisconnect();

Fetch data from array return in redis command

I have a code
var redis = require("redis"), client = redis.createClient(6379, '192.168.1.48');
client.on("error", function (err) {
console.log("Error " + err);
});
client.sadd("hoang","post:1");
client.sadd("hoang","post:2");
client.sadd("hoang","post:3");
client.sadd("hoang","post:4");
client.sadd("hoang","post:5");
client.sadd("hoang","post:7");
client.sadd("lan","post:1");
client.sadd("lan","post:2");
client.sadd("lan","post:3");
client.sadd("lan","post:4");
client.sadd("lan","post:5");
client.sadd("lan","post:6");
var arr = client.sinter("hoang","lan");
console.log(arr.length);
And console print
undefined
How to do i feetch array from redis command.
I don't think client.sinter returns a value, you need a callback function, something like:
client.sinter(["hoang","lan"], function(err, res){
console.log(res, res.length);
})
Please provide a link to the redis client you are using if you need more info.

Categories

Resources