nodejs mysql getting the id of an inserted row
To retrieve the ID of an inserted row in MySQL using Node.js, you can follow these steps:
Create a connection to the MySQL database by using the
mysql
module and thecreateConnection()
function. Pass in the necessary parameters like host, user, password, and database.Use the
query()
method to execute an SQL INSERT statement to insert a new row into the table. This method takes two arguments: the SQL statement and a callback function.In the callback function, you can check for any errors that occurred during the query execution. If there are no errors, you can use the
insertId
property of theresult
object to get the ID of the inserted row.Finally, you can close the database connection by calling the
end()
method on the connection object.
Here is an example of how you can implement these steps in your Node.js code:
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'your_database',
});
connection.connect();
const sql = 'INSERT INTO your_table (column1, column2) VALUES (?, ?)';
const values = ['value1', 'value2'];
connection.query(sql, values, (error, result) => {
if (error) {
throw error;
}
console.log('Inserted row ID:', result.insertId);
});
connection.end();
Please note that you will need to replace 'your_username'
, 'your_password'
, 'your_database'
, 'your_table'
, 'column1'
, and 'column2'
with your actual MySQL credentials and table/column names.
I hope this explanation helps!