const mysql = require('mysql');
// Create a connection to the database
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydatabase'
});
// Connect to the database
connection.connect((err) => {
if (err) {
return console.error('Error connecting: ' + err.stack);
}
console.log('Connected as ID ' + connection.threadId);
// Create a new user
const newUser = { name: 'John Doe', email: '[email protected]' };
connection.query('INSERT INTO users SET ?', newUser, (error, results) => {
if (error) {
return console.error('Error inserting user: ' + error.stack);
}
console.log('User created with ID: ' + results.insertId);
// Read users
connection.query('SELECT * FROM users', (error, results) => {
if (error) {
return console.error('Error fetching users: ' + error.stack);
}
console.log('Users: ', results);
// Update a user
const userId = results[0].id; // ID of the first user
const updatedUser = { name: 'Jane Doe', email: '[email protected]' };
connection.query('UPDATE users SET ? WHERE id = ?', [updatedUser, userId], (error, results) => {
if (error) {
return console.error('Error updating user: ' + error.stack);
}
console.log('User updated: ', results.affectedRows);
// Delete a user
connection.query('DELETE FROM users WHERE id = ?', userId, (error, results) => {
if (error) {
return console.error('Error deleting user: ' + error.stack);
}
console.log('User deleted: ', results.affectedRows);
// Close the connection
connection.end();
});
});
});
});
});