nodejs insert and update to database
nodejsHere 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.
Other Article on Tag nodejs
- - axios Request path contains unescaped characters
- - CryptoJS.HmacSHA256 Cannot read properties of undefined (reading 'sigBytes')
- - encrypt by java and decrypt by node
- - fetch function mode sors, no-cors, same-origin
- - How to set value for NODE_TLS_REJECT_UNAUTHORIZED
- - it error Request path contains unescaped characters
- - java vs nodejs
- - nodejs add redis
- - nodejs call api get request
- - nodejs connect mysql database