
Mysql Insert Into in NodeJs
Inserting data into a MySQL database using Node.js is super simple! Here's how to do it using both mysql
and mysql2
.
✅ Step 1: Install MySQL Package
Choose one of these:
npm install mysql const mysql = require('mysql');const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'myDatabase'});connection.connect((err) => { const mysql = require('mysql2/promise');async function insertUser() { const connection = await mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'myDatabase' }); const sql = 'INSERT INTO users (name, email, age) VALUES (?, ?, ?)'; const values = ['Bob', 'bob@example.com', 30]; const [result] = await connection.execute(sql, values); console.log('Record inserted! ID:', result.insertId); await connection.end();}insertUser();
🧠 Bonus: Insert Multiple Rows at Once
const sql = 'INSERT INTO users (name, email, age) VALUES ?';const values = [ ['Tom', 'tom@example.com', 28], ['Jerry', 'jerry@example.com', 24]];connection.query(sql, [values], (err, result) => { if (err) throw err; console.log('Inserted rows:', result.affectedRows);});
🧪 Table Example (users)
CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), email VARCHAR(255), age INT);