nodejs insert and update to database

nodejs

Here is an example of how you can perform a MySQL INSERT and UPDATE using Node.js:

const mysql = require('mysql');

// Create a connection to the database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'your_username',
  password: 'your_password',
  database: 'your_database'
});

// Connect to the database
connection.connect();

// INSERT a new record
const insertSQL = "INSERT INTO users (name, email) VALUES (?, ?)";
const insertValues = ['John', '[email protected]'];
connection.query(insertSQL, insertValues, (error, results, fields) => {
  if (error) throw error;
  console.log(`Inserted ${results.affectedRows} row(s)`);
});

// UPDATE an existing record
const updateSQL = "UPDATE users SET name = ? WHERE email = ?";
const updateValues = ['John Smith', '[email protected]'];
connection.query(updateSQL, updateValues, (error, results, fields) => {
  if (error) throw error;
  console.log(`Updated ${results.affectedRows} row(s)`);
});

// Disconnect from the database
connection.end();

This code creates a connection to a MySQL database, then performs an INSERT and an UPDATE using the connection.query() method. The connection.query() method takes an SQL string and an array of values as its arguments, and it returns a result object that contains information about the query. The error, results, and fields arguments of the callback function are the error, the result object, and the fields object, respectively.