if I have a query like the following:
var queryString = "INSERT INTO pid SET title = '" + randomTitle + "', poc = '" + random + "';"
connection.query(queryString, function(err, rows, fields) {
...(do something here)
});
, is there a way I can retrieve information for the just-inserted row without performing a new query (in my particular case, I want the auto-generated primary key value).
For instance, can I use the construct with the "query" object (below) and then perhaps use one of the query.on callback to retrieve the information about the just-inserted row?:
var query = connection.query(queryString, function(err, rows, fields) {
query.on('fields', function(fields) {
... get the field information?
});
query.on('result', function(row) {
.. get the field information?
});
});
If not via the query callbacks, is there another way? Thanks for any response!
If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL.
Once you have MySQL up and running on your computer, you can access it by using Node. js. To access a MySQL database with Node. js, you need a MySQL driver.
According to docs it is possilbe. Notice that callback function of insert query does not have rows
and fields
but only result
parameter:
connection.query(queryString, function(err, result) {
if (err) {
// handle error
}
console.log(result.insertId); // prints inserted id
}
Your query is also vulnerable to sql injection. It should look like this:
var queryString = "INSERT INTO pid SET title = ?, poc = ?";
connection.query(queryString, [randomTitle, random], function(err, result) {
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With