i have a simple insert query that looks like that:
let sql = "INSERT into users(name, date) VALUES ('"+name+"', '"+date+"')";
connection.query(sql, (err, result) => {
if(err) {
res.status(500);
} else {
res.send(result) // we have here an object that has only the inserted id
}
});
which i really want is getting the inserted row data not just the id without making another select query to get them.
is there is a way to make that happens in one query?
If you are using:
// include mysql module var mysql = require('mysql');
The mysql module won't return data on the insert's query. It's returning:
Number of rows affected, Number of records affected with the warning, Message
If you wanna get data that you inserted, you should use a query builder or ORM like Sequelize. Sequelize Documentation.
You can get last inserted id using the code below:
SQLconnnection.query(sql, (err, result) => {
if(err) {
console.error(err);
} else {
console.log(result) ;
/*Output=>{affectedRows: 1
changedRows: 0
fieldCount: 0
insertId: 1 =>Last inserted ID Here
message: ""
protocol41: true
serverStatus: 2
warningCount: 0}*/
console.log(result.insertId);//=>last inserted id get
}
});
You can use this to retrieve the
let sql = "INSERT into users(name, date) VALUES ('"+name+"', '"+date+"') ; SELECT * FROM users WHERE id = SCOPE_IDENTITY()";
connection.query(sql, (err, result) => {
if(err) {
res.status(500);
} else {
res.send(result) // we have here an object that has only the inserted id
}
});
SCOPE_IDENTITY() Returns the last identity value inserted
Related
I want to write a query in MySQL for filtering. For example, if there is a column id in table table1 where the filter values for id come in a POST request body, saved in variable A. I want to extract the matching rows if A is not empty and return all rows otherwise. I am not sure about using IN with WHERE.
SELECT * FROM table1 WHERE id IN (A)
One option is that I return all rows from the database and use JavaScript filters, but I don't want to return all rows and expose the entire table to user.
NOTE: A can be a single value, a tuple or an array.
If you use javascript, use A.join(), and sanitize your POST.
var your_post = [1, 2, 3];
var A = your_post.join();
if (A == '') {
var sql = 'SELECT * FROM table1';
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
} else {
var sql = 'SELECT * FROM table1 WHERE id IN (?)';
con.query(sql, [A], function (err, result) {
if (err) throw err;
console.log(result);
});
}
thanks for reading.
I have a table with 3 fields, one is the ID, which autoincrements and I can´t access it from my Node.js server since it's added by MySql. Another field contains a string, and the last field should be the sum of the 3 first letters of the string field, added to the id.
The thing is, when I do my query I can't just add them up because the id doesn´t exist until the query is sent to the DB.
What should I do? It'd be such an inconvenience to handle the ID autoincrement from the API.
Thanks for your time!
After you insert the row, you can get its ID and update the third column.
connection.query('INSERT INTO yourTable (name) VALUES (?)', [name], function(err, result) {
if (err) {
throw err;
}
let code = name.substr(0, 3) + result.insertId;
connection.query('UPDATE yourTable SET code = ? WHERE id = ?', [code, result.insertId], function(err) {
if (err) {
throw err;
}
});
});
However, this won't work if you're inserting multiple rows in bulk, since result.insertId is just the last row that was inserted.
You could update all the rows where the code
connection.query('INSERT INTO yourTable (name) VALUES ?', names.map(n => [n]), function(err, result) {
if (err) {
throw err;
}
connection.query('UPDATE yourTable SET code = CONCAT(SUBSTR(name, 1, 3), id) WHERE code IS NULL', function(err) {
if (err) {
throw err;
}
});
});
My query:
pool.query("SELECT MAX(ID) FROM `games` WHERE status IN('0','1') LIMIT 1", (err, row) => {
if(err) return console.log("err getting the game.");
currentGame = row[0];
console.log(currentGame);
});
Current Result:
RowDataPacket { 'MAX(ID)': 1 }
Desired Result:
1
How do I get just the value and not include the other stuff?
Try adding an alias to your count query, and then access it:
pool.query("SELECT MAX(ID) AS max_id FROM games WHERE status IN ('0','1')", (err, row) => {
if(err) return console.log("err getting the game.");
currentGame = row[0].max_id;
console.log(currentGame);
});
Note: A max query by definition will always return only a single record result set (in the absence of GROUP BY), so there is no need for LIMIT 1.
I'm trying to update a TEXT field in a MYSQL table. I can't get the UPDATE query to work, even though the original INSERT attempt works fine when the user doesn't exist.
The purpose of the function is to INSERT new row if the user doesn't exist yet, and to UPDATE the textColumn (that always contains a JSON) if the user already exists in the table.
My code:
let first = 'jake';
let last = 'mcdonald';
let first_json = JSON.stringify({a:7, b:7});
let second_json = JSON.stringify({a:'updated'});
const row = {
name: first,
last_name: last,
textColumn: first_json,
}
db.query(`SELECT * FROM tableName
WHERE name="${first}"
AND last_name="${last}"`, (err, result) => {
if (err) console.log(err);
if (result.length < 1) {
db.query(`INSERT INTO tableName SET ?`, row, (err, result) => {
console.log('NEW ROW CREATED: ', result);
})
} else if (result.length > 0) {
console.log('ROW EXISTS');
db.query(`UPDATE tableName
SET textColumn=${second_json}
WHERE name="${first}"
AND last_name="${last}"`, (err, result) => {
console.log('UPDATED: ', result);
}
)
}
}
)
the else if section is what is giving me issues: I reach the inside console.log('ROW EXISTS') but the Update query logs "undefined".
The same UPDATE query works if I try to UPDATE tableName SET name="someNewName" WHERE last_name="original_last_name", but nothing happens when I try to UPDATE the textColumn.
I have statements:
INSERT INTO infotbl(name, phone) VALUES('Alex', '9999999');
and update it:
UPDATE infotbl SET name = 'Alex Johnes', phone = '999 34356063' WHERE id = 1;
then delete:
DELETE FROM infotbl WHERE id = 1;
I've inserted successfully, when I update and delete rows has been change in MySQL. but my code in Node return affected rows = 0. Why?. There is my function to update and delete in Node:
function deleteCustomer (id, callback) {
db.connection.query("DELETE FROM infotbl WHERE id=?", id, (err, result) => {
if (err) throw err;
if (result.affectedRows > 0)
callback(true);
else
callback(false);
});
};
and update function:
function updateCustomer(id, name, phone, callback) {
db.connection.query("UPDATE infotbl SET name = ?, phone = ? WHERE id = ?;", [name, phone, id], (err, result) => {
if (err) throw err;
if (result.affectedRows > 0)
callback(true);
else
callback(false);
});
}
Why node return 0 affected rows when database executed successfully?
The most likely explanation is that there are no rows that satisfy the conditions in the UPDATE and DELETE statements. That is, there are no rows with id value equal to 1.
An UPDATE could affect zero rows if the conditions match one or more rows, but the changes applied to the row result in "no change"... that is, the columns being modified already have the values being assigned.
An UPDATE or DELETE that executes successfully, but affects zero rows, is still considered successful.