🗄️ Node.js – MySQL: CRUD Operations
Estimated reading: 3 minutes 419 views

Node.js – MySQL Insert Into – Add Records to Your Database with Node.js


Introduction – Why Insert Data into MySQL with Node.js?

Inserting data into a MySQL database is a core operation for any backend app. With Node.js and the mysql module, you can easily send SQL INSERT statements to store user inputs, logs, transactions, product entries, and more.

In this guide, you’ll learn:

  • How to insert single and multiple records
  • Use parameterized queries for security
  • Handle insert callbacks and inserted IDs
  • Best practices for structured inserts

Setup – MySQL Connection File (db.js)

Before inserting data, ensure your connection is configured:

const mysql = require('mysql');

const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'testdb'
});

db.connect((err) => {
  if (err) throw err;
  console.log('Connected to MySQL');
});

module.exports = db;

Insert a Single Record

const db = require('./db');

const user = { name: 'Alice', email: 'alice@example.com' };

db.query('INSERT INTO users SET ?', user, (err, result) => {
  if (err) throw err;
  console.log('Inserted ID:', result.insertId);
});

Output:

Inserted ID: 1

Using ? placeholders protects against SQL injection.


Insert Multiple Records at Once

const db = require('./db');

const users = [
  ['Bob', 'bob@example.com'],
  ['Charlie', 'charlie@example.com']
];

db.query('INSERT INTO users (name, email) VALUES ?', [users], (err, result) => {
  if (err) throw err;
  console.log('Inserted rows:', result.affectedRows);
});

Output:

Inserted rows: 2

Insert with Named Placeholders (for readability)

const user = { name: 'David', email: 'david@example.com' };
const sql = 'INSERT INTO users SET ?';

db.query(sql, user, (err, result) => {
  if (err) throw err;
  console.log('New user ID:', result.insertId);
});

This approach makes it easier to work with object-based APIs or form submissions.


Best Practices for INSERT Queries in Node.js

Practice Why It’s Important
Use parameterized queries (?)Prevents SQL injection
Handle insertId from resultUseful for linking related records
Use async functions in productionBetter scalability using mysql2/promise
Validate input before insertingAvoid inserting bad or incomplete data
Use created_at timestampsAutomatically record when the row was added

Summary – Recap & Next Steps

You’ve successfully learned how to insert records into a MySQL table using Node.js, handle multiple rows, and use placeholders for safer code.

Key Takeaways:

  • Use INSERT INTO table SET ? for object inserts
  • Use parameterized queries to prevent SQL injection
  • Capture insertId from results for reference
  • Easily insert multiple rows with 2D arrays

Real-world relevance:
Used in user registration systems, blog content creation, admin dashboards, logging tools, and transaction processing.


FAQs – Inserting Data into MySQL with Node.js


How do I insert form data into MySQL from Node.js?
Collect form inputs using req.body (via Express), then use:

db.query('INSERT INTO users SET ?', req.body, callback);

Can I insert multiple rows at once in MySQL with Node.js?
Yes. Use VALUES ? and pass a 2D array:

[['name1', 'email1'], ['name2', 'email2']]

How do I get the ID of the inserted row?
Use result.insertId in the callback.


What happens if I insert a duplicate email (with UNIQUE constraint)?
MySQL will throw an error. You should catch it and send an appropriate response.


Is mysql2 better than mysql for inserts?
mysql2 supports Promises and async/await, making it ideal for modern apps.


Share Now :
Share

➕ Node.js – MySQL Insert Into

Or Copy Link

CONTENTS
Scroll to Top