Node Js SQL syntax - mysql

i am a beginner programmer of nodejs with mysql. while making a crud application using node js with mysql ran into the problem with You have an error in your SQL syntax
when i trying to search the record what i tried so far i attached below.i couldn't find the error here.
Search
server.get('/api/student/:id',(req, res) => {
var sql = "SELECT * FROM student WHERE id=" + req.params.id;
con.query(sql, function (err, result, fields) {
if (err) throw err;
res.end(JSON.stringify(result));
});
});
i attached the full error below.
Error: ER_PARSE_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 ':3' at line 1
at Query.Sequence._packetToError (E:\nodemysqll\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Query.ErrorPacket (E:\nodemysqll\node_modules\mysql\lib\protocol\sequences\Query.js:79:18)
at Protocol._parsePacket (E:\nodemysqll\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (E:\nodemysqll\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (E:\nodemysqll\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (E:\nodemysqll\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (E:\nodemysqll\node_modules\mysql\lib\Connection.js:88:28)
at Socket.<anonymous> (E:\nodemysqll\node_modules\mysql\lib\Connection.js:526:10)
at Socket.emit (node:events:390:28)
at addChunk (node:internal/streams/readable:315:12)
--------------------
at Protocol._enqueue (E:\nodemysqll\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Connection.query (E:\nodemysqll\node_modules\mysql\lib\Connection.js:198:25)
at E:\nodemysqll\server.js:76:19
at Layer.handle [as handle_request] (E:\nodemysqll\node_modules\express\lib\router\layer.js:95:5)
at next (E:\nodemysqll\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (E:\nodemysqll\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (E:\nodemysqll\node_modules\express\lib\router\layer.js:95:5)
at E:\nodemysqll\node_modules\express\lib\router\index.js:284:15
at param (E:\nodemysqll\node_modules\express\lib\router\index.js:365:14)
at param (E:\nodemysqll\node_modules\express\lib\router\index.js:376:14) {
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: "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 ':3' at line 1",
sqlState: '42000',
index: 0,
sql: 'SELECT * FROM student WHERE id=:3'

Related

"Error: ER_NO_SUCH_TABLE: Table 'managementapp.medicament' doesn't exist"

I'm working in simple CRUD application using react, node and express.. so i connected to my mysql data base "managementapp" and i tried to insert information in my db, but im always getting the error "table doesn't exist while i tested locally and it works properly in mysql wrokbensh and im so sure that im spelling the name of my table correctly. so this the code of App.js for react :
function App() {
const [name,setName]=useState("");
const [description,setDescription]=useState("");
const [number,setNumbre]=useState(0);
const addMedicament = () => {
console.log(name);
Axios.post("http://localhost:3001/create",
{name:name,
description:description,
number:number,
}).then(()=>{
console.log("succes");
});
};
and this my index.js for backend part
const db=mysql.createConnection({
user:"root",
host:"localhost",
password:"",
database:"managementapp",
});
app.post("/create", (req, res) => {
console.log(req.body);
const name=req.body.name;
const description=req.body.description;
const number=req.body.number;
db.query(
"insert into medicament (name,description,number) VALUES (?,?,?);",
[name,description,number],
(err,result) =>{
if (err)
{ console.log(err);
}
else { res.send("Values inserted !! ");
}
}
);
});
so im always getting this error
{ name: 'erty', description: 'rtyuk', number: '86' }
Error: ER_NO_SUCH_TABLE: Table 'managementapp.medicament' doesn't exist
at Query.Sequence._packetToError (C:\Users\Chahine\Management\server\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Query.ErrorPacket (C:\Users\Chahine\Management\server\node_modules\mysql\lib\protocol\sequences\Query.js:79:18)
at Protocol._parsePacket (C:\Users\Chahine\Management\server\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (C:\Users\Chahine\Management\server\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (C:\Users\Chahine\Management\server\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (C:\Users\Chahine\Management\server\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (C:\Users\Chahine\Management\server\node_modules\mysql\lib\Connection.js:88:28)
at Socket.<anonymous> (C:\Users\Chahine\Management\server\node_modules\mysql\lib\Connection.js:526:10)
at Socket.emit (events.js:400:28)
at addChunk (internal/streams/readable.js:290:12)
--------------------
at Protocol._enqueue (C:\Users\Chahine\Management\server\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Connection.query (C:\Users\Chahine\Management\server\node_modules\mysql\lib\Connection.js:198:25)
at C:\Users\Chahine\Management\server\index.js:25:8
at Layer.handle [as handle_request] (C:\Users\Chahine\Management\server\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Chahine\Management\server\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\Chahine\Management\server\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\Chahine\Management\server\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\Chahine\Management\server\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\Chahine\Management\server\node_modules\express\lib\router\index.js:341:12)
at next (C:\Users\Chahine\Management\server\node_modules\express\lib\router\index.js:275:10)
{
code: 'ER_NO_SUCH_TABLE',
errno: 1146,
sqlMessage: "Table 'managementapp.medicament' doesn't exist",
sqlState: '42S02',
index: 0,
sql: "insert into medicament (name,description,number) VALUES ('erty','rtyuk','86');"
}
i was searching since last night and i found that the problem was with my mysql installation .. so i uninstalled it and reinstall it then i changed the port from 3306 to another cause it was already in use .. then i had the error about
Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol
requested by server; consider upgrading MySQL client
so i just get into mysql and run a query saying root is fine using old mysql_native_password method for authentication:
ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY 'YourRootPassword';
and everything went right. thanks to Aidin's explanation.

Insert Errors when run from js, xampp shell worked fine with same sql

heres the sql im trying to run, when i use xampp i am able to get the responce to insert my table. but if i pass the sql into my query function i am unable to get the query to insert into my table. and i get the below error instead:
START TRANSACTION;
INSERT INTO address_tbl (address_ln_1, address_ln_2, address_town, address_county, address_postcode) VALUES ('place', '', 'Town', 'county', 'postcode');
SELECT LAST_INSERT_ID();
COMMIT;
using the js:
var query= function (sql){
return new Promise(resolve => {
con.query(sql, (err, result) => {
if(err) throw err;
resolve(result);
});
});
}
error:
C:\node_modules\mysql\lib\protocol\Parser.js:437
throw err; // Rethrow non-MySQL errors
^
Error: ER_PARSE_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 'INSERT INTO address_tbl (address_ln_1, address_ln_2, address_town, address_count' at line 1
at Query.Sequence._packetToError (C:\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Query.ErrorPacket (C:\node_modules\mysql\lib\protocol\sequences\Query.js:77:18)
at Protocol._parsePacket (C:\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (C:\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (C:\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (C:\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (C:\node_modules\mysql\lib\Connection.js:91:28)
at Socket.<anonymous> (C:\node_modules\mysql\lib\Connection.js:525:10)
at Socket.emit (events.js:198:13)
at addChunk (_stream_readable.js:288:12)
--------------------
at Protocol._enqueue (C:\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Connection.query (C:\node_modules\mysql\lib\Connection.js:201:25)
at resolve (C:\db.js:18:13)
at new Promise (<anonymous>)
at Object.query (C:\db.js:17:12)
at insert (C:\utl\order_model.js:16:8)
at Order.insert (C:\utl\order_model.js:99:9)
at utill.calculate_cart (C:\routes\orderRouter.js:65:15)
at pm.getProducts.productlist (C:\utl\utill.js:22:9)
at Object.getProducts (C:\utl\products_model.js:27:9)
[nodemon] app crashed - waiting for file changes before starting...
So just reading the error message and comparing to the (working) query above:
Working: INSERT INTO address_tbl (address_ln_1, address_ln_2, address_town, address_county, address_postcode) VALUES ('place', '', 'Town', 'county', 'postcode');
Error Message: 'INSERT INTO address_tbl (address_ln_1, address_ln_2, address_town, address_count'
You're missing some of the parameters for your Table Insert. I'd look at why that is.

mysqljs ER_PARSE_ERROR in valid request

I'm using mysqljs and I want to delete a row in a table with its id:
class_id is the id (string).
connection.query(
`DELETEĀ FROM classes WHERE id = ?`, [class_id], (err, result) => {
if (err) throw(err);
resolve();
}
);
Connection:
global.connection = mysql.createPool({
connectionLimit : 10,
host : config.mysql.hostname,
user : config.mysql.user,
password : config.mysql.password,
database : config.mysql.database,
charset: 'utf8'
});
But I got this error:
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 'DELETE FROM classes WHERE id = 'C2'' at line 1
at Query.Sequence._packetToError (C:\Users\admin\Documents\main\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Query.ErrorPacket (C:\Users\admin\Documents\main\node_modules\mysql\lib\protocol\sequences\Query.js:77:18)
at Protocol._parsePacket (C:\Users\admin\Documents\main\node_modules\mysql\lib\protocol\Protocol.js:278:23)
at Parser.write (C:\Users\admin\Documents\main\node_modules\mysql\lib\protocol\Parser.js:76:12)
at Protocol.write (C:\Users\admin\Documents\main\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (C:\Users\admin\Documents\main\node_modules\mysql\lib\Connection.js:91:28)
at Socket.<anonymous> (C:\Users\admin\Documents\main\node_modules\mysql\lib\Connection.js:502:10)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
--------------------
I tried to execute the request manually and it works great.
Can someone help me?

ER_PARSE_ERROR happens

I want to do web scraping.I wrote codes
var connection = require('./mysqlConnection');
var c = new Crawler({
maxConnections : 10,
callback : function (error, result, $) {
if(error){
console.log(error);
}else{
const data = $(".test");
for(var i = 0; i < data.length; i ++){
const item = $(data[i]).text();
var query = 'INSERT INTO crawling (item) VALUES ("' + item + '")';
connection.query(query, function(err, rows) {
console.log(err);
});
}
}
}
});
c.queue('https://xxxxxxxxxx.com');
When I run this codes,const item could be gotten halfway through,but
{ 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 'June18th
")' at line 1
at Query.Sequence._packetToError (/Users/xxx/xxx/node_modules/mysql/lib/protocol/sequences/Sequence.js:52:14)
at Query.ErrorPacket (/Users/xxx/xxx/node_modules/mysql/lib/protocol/sequences/Query.js:77:18)
at Protocol._parsePacket (/Users/xxx/xxx/node_modules/mysql/lib/protocol/Protocol.js:279:23)
at Parser.write (/Users/xxx/xxx/node_modules/mysql/lib/protocol/Parser.js:76:12)
at Protocol.write (/Users/xxx/xxx/node_modules/mysql/lib/protocol/Protocol.js:39:16)
at Socket.<anonymous> (/Users/xxx/xxx/node_modules/mysql/lib/Connection.js:103:28)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
--------------------
at Protocol._enqueue (/Users/xxx/xxx/node_modules/mysql/lib/protocol/Protocol.js:145:48)
at Connection.query (/Users/xxx/xxx/node_modules/mysql/lib/Connection.js:208:25)
at Object.callback (/Users/xxx/xxx/app.js:135:24)
at Crawler._onInject (/Users/xxx/node_modules/node-webcrawler/lib/crawler.js:428:13)
at /Users/xxx/node_modules/node-webcrawler/lib/crawler.js:395:11
at Crawler._inject (/Users/xxx/node_modules/node-webcrawler/lib/crawler.js:154:9)
at Crawler._onContent (/Users/xxx/node_modules/node-webcrawler/lib/crawler.js:394:7)
at Request._callback (/Users/xxx/node_modules/node-webcrawler/lib/crawler.js:332:14)
at Request.self.callback (/Users/xxx/node_modules/node-webcrawler/node_modules/request/request.js:187:22)
at emitTwo (events.js:126:13)
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: '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 \'June18th"\n \n \n ")\' at line 1',
sqlState: '42000',
index: 0,
sql: 'INSERT INTO crawling (title) VALUES (" \n I went to Paris at"June18th"because\n \n \n ")' }
I really cannot understand why such a error happens.I think \n causes this error, so I rewrote
const item = $(data[i]).text().replace("\n", '');
but same error happens.What is wrong in my codes?How should I fix this?
try changing: connection.query(query, function(err, rows) {
to connection.query([query], function(err, rows) {
it may need [] around it
You are adding the double quotes in your query to delimit the text in the insert statement, but you don't know if the incoming text will have double quotes too, hence the statement got malformed:
'INSERT INTO crawling (title) VALUES (" .. "June18th".. ")'
So, by "June18th" the sql went wrong.
Escaping the incoming text is a good practice, because you avoid sql injection and avoid these problems too; usually mysql(or any other database) modules have built-in escaping, using certain syntax in the query, or calling the escaping function directly. like this module https://github.com/mysqljs/mysql#escaping-query-values

I just cant find a fitting solution for this MySQL "Exists()" error

I already searched stackoverflow for like an hour, but no solution can solve my problem.
I want to run this code:
for (var skin in body){
connection.query(`IF NOT EXISTS(SELECT MarketName FROM Skins WHERE MarketName = ?);
THEN
INSERT INTO Skins (MarketName) VALUES (?);
END IF;`,[skin, skin]); }
But if I run this with nodejs, I get this error:
/var/www/html/bot/node_modules/mysql/lib/protocol/Parser.js:80
throw err; // Rethrow non-MySQL errors
^
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 'IF NOT EXISTS(SELECT MarketName FROM
Skins WHERE MarketName = 'Nova | Moon in Li' at line 1
at Query.Sequence._packetToError (/var/www/html/bot/node_modules/mysql/lib/protocol/sequences/Sequence.js:52:14)
at Query.ErrorPacket (/var/www/html/bot/node_modules/mysql/lib/protocol/sequences/Query.js:77:18)
at Protocol._parsePacket (/var/www/html/bot/node_modules/mysql/lib/protocol/Protocol.js:279:23)
at Parser.write (/var/www/html/bot/node_modules/mysql/lib/protocol/Parser.js:76:12)
at Protocol.write (/var/www/html/bot/node_modules/mysql/lib/protocol/Protocol.js:39:16)
at Socket. (/var/www/html/bot/node_modules/mysql/lib/Connection.js:103:28)
at emitOne (events.js:115:13)
at Socket.emit (events.js:210:7)
at addChunk (_stream_readable.js:266:12)
at readableAddChunk (_stream_readable.js:253:11)
--------------------
at Protocol._enqueue (/var/www/html/bot/node_modules/mysql/lib/protocol/Protocol.js:145:48)
at Connection.query (/var/www/html/bot/node_modules/mysql/lib/Connection.js:208:25)
at Request._callback (/var/www/html/bot/index.js:531:16)
at Request.self.callback (/var/www/html/bot/node_modules/request/request.js:186:22)
at emitTwo (events.js:125:13)
at Request.emit (events.js:213:7)
at Request. (/var/www/html/bot/node_modules/request/request.js:1163:10)
at emitOne (events.js:115:13)
at Request.emit (events.js:210:7)
at IncomingMessage. (/var/www/html/bot/node_modules/request/request.js:1085:12)
I would appreciate your help.
MySQL only allows IF statements in programming blocks -- stored procedures, triggers, and the like.
The correct way to do what you want is to create a unique index or constraint on Skins(MarketName). That way, the database ensures integrity of the data. You can do this as:
create unique index unq_skins_marketname on Skins(MarketName);
Then, an attempt to insert a duplicate will result in an error. You can generally avoid this by doing:
insert into skins(marketname)
values (?)
on duplicate key marketname = values(marketname); -- this is a no-op