I'm using MySQL with NodeJS with asyncs and awaits. I'm trying to get the last insertid from my inserted row but keep getting errors.
Here's the async function;
function makeDb( config ) {
const connection = mysql.createConnection( config ); return {
query( sql, args ) {
return util.promisify( connection.query )
.call( connection, sql, args );
},
close() {
return util.promisify( connection.end ).call( connection );
}
};
}
And here's the code which is failing on the queries;
try {
if(tag1){
row_b = await db.query( "SELECT tagid FROM tags WHERE tagname = ?", [tag1]);
const onetagid1 = row_b[0].tagid;
console.log('onetagid1 = ' + onetagid1);
if (row_b > 0){
row_c = await db.query("
INSERT INTO entitytag (tagid1, audioid) VALUES (?,?)
ON DUPLICATE KEY UPDATE tagid1 = ?" [onetagid1, audioid, onetagid1]
);
} else {
row_d = await db.query( 'INSERT IGNORE INTO tags (tagname) VALUES (?)', [tag1]);
var twotagid1 = row_d.insertId;
console.log('twotagid1 2nd = ' + twotagid1);
row_e = await db.query(
"INSERT INTO entitytag (tagid1, audioid) VALUES (?,?)
ON DUPLICATE KEY UPDATE tagid1 = ?" [twotagid1, audioid, twotagid1]
);
}
res.json('json success!');
}
}
And here's the error;
onetagid1 = 30
twotagid1 2nd = 0
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 'I' at line 1
The error is twotagid1 2nd = 0 which should not be zero.
I'm not sure why this works when the other didn't. But I'll post it here hoping someone will be able to spot it;
try {
if(tag1){
row_c = await db.query( "SELECT tagid FROM tags WHERE tagname = ?", [tag1]);
if (row_c.length > 0){
console.log('tag exists in database ');
const tagid1 = row_c[0].tagid;
console.log('tagid1 = ' + tagid1);
row_f = await db.query(
"INSERT INTO entitytag (tagid1, audioid) VALUES (?,?)
ON DUPLICATE KEY UPDATE tagid1 = ?", [tagid1, audioid, tagid1 ]);
} else {
console.log('tag does not exist in database ');
row_d = await db.query( 'INSERT IGNORE INTO tags (tagname) VALUES (?)', [tag1]);
const tagInsertId = row_d.insertId;
console.log('tagInsertId = ' + tagInsertId);
row_e = db.query(
'INSERT INTO entitytag (tagid1, audioid) VALUES (?,?)
ON DUPLICATE KEY UPDATE tagid1 = ?', [tagInsertId, audioid, tagInsertId ]);
}
}
console.log('success!');
res.json(tag1);
}
i am beginner in node.js , i hava an array of json data and i wanted to update my table squad by all the rows of my json array , so i used a loop , and then after i execute , i can only see the json input with console.log(data.players) but there is no response or anything , like the function is dead , no errors , the update is not done , just displaying the entry data
Here the input data:
{"id":1,"email":"d","password":"d","name":"d","price":5,"points":5,"fixture":"d","userid":1,
"players":
[{"id":2724,"firstname":"Lucas Digne","lastname":"Lucas Digne","position":"D","price":0,"rating":"7.3","appearences":1,"goals":0,"assists":0,"cleansheets":0,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/2724.png","teamid":45,"clubid":1,"fixtureid":592848,"points":2},{"id":19599,"firstname":"Emiliano Martínez","lastname":"Emiliano Martínez","position":"G","price":0,"rating":"6.6","appearences":1,"goals":0,"assists":0,"cleansheets":5,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/19599.png","teamid":66,"clubid":1,"fixtureid":592855,"points":11},{"id":2741,"firstname":"Mathew Ryan","lastname":"Mathew Ryan","position":"G","price":0,"rating":"5.0","appearences":1,"goals":0,"assists":0,"cleansheets":0,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/2741.png","teamid":42,"clubid":1,"fixtureid":592851,"points":-1},{"id":289,"firstname":"Andrew Robertson","lastname":"Andrew Robertson","position":"D","price":0,"rating":"7","appearences":1,"goals":0,"assists":0,"cleansheets":0,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/289.png","teamid":40,"clubid":1,"fixtureid":592850,"points":2},{"id":289,"firstname":"Andrew Robertson","lastname":"Andrew Robertson","position":"D","price":0,"rating":"7","appearences":1,"goals":0,"assists":0,"cleansheets":0,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/289.png","teamid":40,"clubid":1,"fixtureid":592850,"points":2},{"id":2726,"firstname":"Kurt Zouma","lastname":"Kurt Zouma","position":"D","price":0,"rating":"7.2","appearences":1,"goals":0,"assists":0,"cleansheets":0,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/2726.png","teamid":49,"clubid":1,"fixtureid":592851,"points":2},{"id":633,"firstname":"İlkay Gündoğan","lastname":"İlkay Gündoğan","position":"M","price":0,"rating":"8.3","appearences":1,"goals":0,"assists":1,"cleansheets":0,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/633.png","teamid":50,"clubid":1,"fixtureid":592852,"points":5},{"id":633,"firstname":"İlkay Gündoğan","lastname":"İlkay Gündoğan","position":"M","price":0,"rating":"8.3","appearences":1,"goals":0,"assists":1,"cleansheets":0,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/633.png","teamid":50,"clubid":1,"fixtureid":592852,"points":5}]}
Here the node.js:
updatefixture:(data,callback)=>{
console.log(JSON.stringify(data));
for(var item of data.players){
pool.query(
'UPDATE squad SET appearences = 1, rating = ? goals = ? assists = ? , cleensheets = ?, redcards = ?, yellowcards = ? , points = ? WHERE id = ? AND fixtureid = ? ',
[
item.id,
item.rating,
item.goals,
item.assists,
item.cleansheets,
item.redcards,
item.yellowcards,
item.points,
item.id,
item.fixtureid
],
);
}
(error,result) => {
if(error){
console.log(error);
return callback(error);
}
return callback(null,result);
}
},
I just want a way to update all rows with the condition that made with where clause and make sure that the rows will be updated, any help for a beginner like me will be so appreciated
It seems you just moved callback of pool.query function outside of the loop.
Try the following:
updatefixture:(data,callback)=>{
function addPlayer(item) {
return new Promise((accept, reject) => {
pool.query('UPDATE squad SET appearences = 1, rating = ? goals = ? assists = ? , cleensheets = ?, redcards = ?, yellowcards = ? , points = ? WHERE id = ? AND fixtureid = ? ',
[
item.id,
item.rating,
item.goals,
item.assists,
item.cleansheets,
item.redcards,
item.yellowcards,
item.points,
item.id,
item.fixtureid
], (error, result) => {
if(error){
reject(error);
} else {
accept(result);
}
});
});
}
console.log(JSON.stringify(data));
Promise.all(data.players.map(addPlayer)).then((result)=>{
console.log(result)
callback(null, result)
}).catch((error)=>{
console.log('Error:', error)
callback(error)
})
},
I want to insert into my table values which I get from my front.
so. I have
const Workers = function (workers) {
this.id = workers.id,
this.workers = workers.workers,
this.room = workers.room,
this.team = workers.team,
this.city = workers.city,
this.hotel_name = workers.hotel_name,
this.address = workers.address
};
Workers.create = (newWorkers, result) => {
sql.query(`INSERT INTO rooms_split (workers, room, hotel_name, address, createdAt, updatedAt) VALUES( ? , ? , ? , ?, DEFAULT, DEFAULT )`,
[newWorkers.workers, newWorkers.room, newWorkers.hotel_name, newWorkers.address], (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
console.log("created splitted room: ", {
id: res.insertId,
...newWorkers
});
result(null, {
id: res.insertId,
...newWorkers
});
});
};
And there is my controller
exports.create = (req, res) => {
console.log("body " + JSON.stringify(req.body));
if (!req.body) {
res.status(400).send({
message: "Content can not be empty!"
});
}
const workers = new Workers({
workers: req.body.workers,
room: req.body.room,
hotel_name: req.body.hotel_name,
address: req.body.address
});
Workers.create(workers, (err, data) => {
if (err)
res.status(500).send({
message: err.message || "Some error occurred while creating the Alias."
});
else res.send(data);
});
}
Output from
console.log("body " + JSON.stringify(req.body));
is
body {"workers":["John Snow","Juri Boyka"],"room":"45","hotel_name":"Test Hamburg","address":"Hamburg 5, test Strase"}
and it looks fine but when is time to insert it into table I got error
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 ''Juri Boyka', `room` = '45', `team` = NULL, `city` = NULL, `hotel_na' at line 1",
sqlState: '42000',
index: 0,
sql: "INSERT INTO rooms_split SET `id` = NULL, `workers` = 'John Snow', 'Juri Boyka', `room` = '45', `team` = NULL, `city` = NULL, `hotel_name` = 'Test Hamburg', `address` = 'Hamburg 5, test Strase'"
}
I kniw what this error means but I have no idea why when I want to make query nodejs(?) separates my value so instead ['something','something2'] I got 'something', 'something2' and he is right that there are not enough columns
Change
[newWorkers.workers, newWorkers.room, newWorkers.hotel_name, newWorkers.address]
to
[newWorkers.workers.join(), newWorkers.room, newWorkers.hotel_name, newWorkers.address]
since the workers data type in MySQL is varchar. Therefore, you'll need to stringify your incoming workers array
I have a problem running the following SQL query to my MySQL database with nodeJS and the node-mysql packe which is added with npm.
INSERT INTO locations (locationID,name,latitude,longitude)
SELECT '214777725','Bryans Road,
Maryland','38.628055556','-77.081666667'
FROM dual WHERE NOT EXISTS
(SELECT * FROM locations WHERE locationID = '214777725')
I've tried the following code:
var arrValues = [ -12.9747, -38.4767, 213287181, 'Salvador, Brazil' ];
var arrNames = [ 'latitude', 'longitude', 'locationID', 'name' ];
var locationID = "214777725";
if(imageData["locationID"] != null) {
var query = "INSERT INTO locations ? ";
query = query + " SELECT (?)";
query = query + " FROM dual WHERE NOT EXISTS";
query = query + " (SELECT * FROM locations WHERE locationID = ?)";
console.log(query);
connection.query(query, [arrNames,arrValues,locationID], function(err,res)
{
if(err)
{
console.log(err);
}
else
{
console.log("Insert-Success: " +id);
}
});
}
Running this the console writes following error:
{
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlState: '42000',
index: 0
}
I hope somebody can help.
It looks like you need to use the .toString(); function on your arrays.
connection.query(query, [arrNames.toString(),arrValues.toString(),locationID], function(err,res)
{ ...
what is wrong with this logic?
var selectString = 'SELECT EXISTS(SELECT 1 FROM users WHERE user="'+username+'")';
var queryUserExists = connection.query(selectString);
var resultsLength = queryUserExists._results.length;
console.log(queryUserExists);
if(resultsLength > 0){
socket.write("fail user already exists"+"\r\n");
} else {
console.log('insert=');
var query = connection.query (
'INSERT INTO users '+
'SET user = ?, password = ?, token = ?',
[username, password, token]
);
socket.write("success"+"\r\n");
}
resultsLength is always returned zero.
What is the proper way to use this query?
returned object:
sql: 'SELECT 1 FROM users WHERE user = \'a new user is my name\' ORDER BY user LIMIT 1',
typeCast: true,
nestTables: false,
_resultSet: null,
_results: [],
_fields: [],
_index: 0,
_loadError: null }
The proper code: thanks to https://stackoverflow.com/users/722783/mahmoud-gamal for the database query that is optimized!
connection.query("SELECT 1 FROM users WHERE user = '"+username+"' ORDER BY user LIMIT 1", function (error, results, fields) {
if (error) {
console.log(error);
socket.write("fail internal error"+"\r\n");
}
if (results.length > 0) {
console.log('fail');
socket.write("fail user already exists"+"\r\n");
} else {
console.log('insert');
var query = connection.query (
'INSERT INTO users '+
'SET user = ?, password = ?, token = ?',
[username, password, token]
);
socket.write("success"+"\r\n");
}
console.log(results);
});
Try this:
SELECT 1
FROM users
WHERE EXISTS (SELECT 1
FROM users
WHERE user = 'username')
ORDER BY user
LIMIT 1;
Or: Why not:
SELECT 1
FROM users
WHERE user = 'username'
ORDER BY user
LIMIT 1;
Note that:
ORDER BY user
LIMIT 1;
Are just for performance.