Node.js MySQL INSERT INTO Query Examples
Node.js MySQL INSERT INTO query is used to add one or more rows to a MySQL table from a Node.js application. In a typical program, you connect to the database using the mysql module, run an INSERT INTO statement, and read the result object returned by MySQL.
This tutorial shows how to insert a single row, insert multiple rows in one query, use Node.js variables with placeholders, and read values such as affectedRows and insertId from the result object.
We will cover the following scenarios with examples.
- Database table used for Node.js MySQL INSERT examples
- Node.js MySQL INSERT one row into a table
- Node.js MySQL INSERT using variables and placeholders
- Node.js MySQL INSERT multiple rows into a table
- Accessing properties of Result Object
- Node.js MySQL INSERT INTO FAQs
Database table used for Node.js MySQL INSERT examples
The examples in this tutorial use a database named studentsDB and a table named students. The table has columns for student name, roll number, and marks.
CREATE DATABASE IF NOT EXISTS studentsDB;
USE studentsDB;
CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
rollno INT NOT NULL,
marks INT NOT NULL
);
If your table already exists, make sure the column names in the query match your table. A mismatch in column names or data types is one of the common reasons for an INSERT query to fail.
Example 1 – INSERT Row into MySQL Table via Node.js
In this example, we will connect to MySQL database, and insert a record into students table.
insertIntoExample.js
// include mysql module
var mysql = require('mysql');
// create a connection variable with the required details
var con = mysql.createConnection({
host: "localhost", // ip address of server running mysql
user: "arjun", // user name to your mysql database
password: "password", // corresponding password
database: "studentsDB" // use the specified database
});
// make to connection to the database.
con.connect(function(err) {
if (err) throw err;
// if connection is successful
con.query("INSERT INTO students (name,rollno,marks) values ('Anisha',12,95)", function (err, result, fields) {
// if any error while executing above query, throw error
if (err) throw err;
// if there is no error, you have the result
console.log(result);
});
});
Run above Node.js MySQL program in Terminal.
Output
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node insertIntoExample.js
OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0 }
The value of affectedRows is 1, so one row was inserted. If the table has an auto-increment primary key, MySQL can also return the generated id through insertId.
Node.js MySQL INSERT using variables and placeholders
When values come from variables, form inputs, or API requests, do not build the SQL query by joining strings manually. Use placeholders with the ? symbol and pass the values separately. This keeps the query easier to read and helps avoid problems with quotes and special characters.
The following example inserts one student record using Node.js variables.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "arjun",
password: "password",
database: "studentsDB"
});
var studentName = "Rahul";
var rollNumber = 18;
var studentMarks = 91;
con.connect(function(err) {
if (err) throw err;
var sql = "INSERT INTO students (name, rollno, marks) VALUES (?, ?, ?)";
var values = [studentName, rollNumber, studentMarks];
con.query(sql, values, function(err, result) {
if (err) throw err;
console.log("Rows inserted: " + result.affectedRows);
console.log("Inserted row id: " + result.insertId);
});
});
Output
Rows inserted: 1
Inserted row id: 4
The exact value of insertId depends on the current auto-increment value in your table. If your table does not have an auto-increment column, insertId may be 0.
Example 2 – INSERT Multiple Rows into MySQL Table via Node.js
In this example, we will connect to MySQL database, and insert three records into students table in a single statement.
insertMulIntoExample.js
// include mysql module
var mysql = require('mysql');
// create a connection variable with the required details
var con = mysql.createConnection({
host: "localhost", // ip address of server running mysql
user: "arjun", // user name to your mysql database
password: "password", // corresponding password
database: "studentsDB" // use the specified database
});
// make to connection to the database.
con.connect(function(err) {
if (err) throw err;
// if connection is successful
var records = [
['Miley', 13, 85],
['Jobin', 14, 87],
['Amy', 15, 74]
];
con.query("INSERT INTO students (name,rollno,marks) VALUES ?", [records], function (err, result, fields) {
// if any error while executing above query, throw error
if (err) throw err;
// if there is no error, you have the result
console.log(result);
});
});
Run above Node.js MySQL program in Terminal.
Output
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node insertMulIntoExample.js
OkPacket {
fieldCount: 0,
affectedRows: 3,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: '&Records: 3 Duplicates: 0 Warnings: 0',
protocol41: true,
changedRows: 0 }
For multiple inserts, the data is passed as an array of rows. Each inner array must follow the same order as the columns in the SQL statement. In this example, each row follows the order name, rollno, and marks.
Accessing properties of Result Object
Once the INSERT INTO Query is executed, MySQL Server responds with a result object. The properties of result object like affectedRows, serverStatus, changedRows etc., could be accessed using DOT (.) operator.
InsertMulIntoExample.js
// include mysql module
var mysql = require('mysql');
// create a connection variable with the required details
var con = mysql.createConnection({
host: "localhost", // ip address of server running mysql
user: "arjun", // user name to your mysql database
password: "password", // corresponding password
database: "studentsDB" // use the specified database
});
// make to connection to the database.
con.connect(function(err) {
if (err) throw err;
// if connection is successful
var records = [
['Jack', 16, 82],
['Priya', 17, 88],
['Amy', 15, 74]
];
con.query("INSERT INTO students (name,rollno,marks) VALUES ?", [records], function (err, result, fields) {
// if any error while executing above query, throw error
if (err) throw err;
// if there is no error, you have the result
console.log(result);
console.log("Number of rows affected : " + result.affectedRows);
console.log("Number of records affected with warning : " + result.warningCount);
console.log("Message from MySQL Server : " + result.message);
});
});
Open a terminal or command prompt and run this script using node command as shown in the following.
Output
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node InsertMulIntoExample.js
OkPacket {
fieldCount: 0,
affectedRows: 3,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: '&Records: 3 Duplicates: 0 Warnings: 0',
protocol41: true,
changedRows: 0 }
Number of rows affected : 3
Number of records affected with warning : 0
Message from MySQL Server : &Records: 3 Duplicates: 0 Warnings: 0
Common result object properties after Node.js MySQL INSERT
The result object gives useful information about the INSERT operation. The most commonly used properties are listed below.
| Property | Meaning after INSERT query |
|---|---|
affectedRows | Number of rows inserted or affected by the query. |
insertId | Auto-increment id generated for the inserted row, when applicable. |
warningCount | Number of warnings returned by MySQL for the query. |
message | Additional message returned by MySQL, often useful for multiple-row inserts. |
changedRows | Usually more relevant for UPDATE queries than INSERT queries. |
How to check inserted rows in MySQL after running Node.js
After running the Node.js program, you can verify the inserted rows directly from MySQL Workbench, MySQL Shell, or the MySQL command-line client. Use a simple SELECT query on the same table.
SELECT id, name, rollno, marks
FROM students
ORDER BY id DESC;
If the inserted rows do not appear, check that the Node.js connection is using the correct database name and that the script did not stop with an error.
Common errors in Node.js MySQL INSERT INTO queries
The following issues are common while inserting data from Node.js into MySQL.
- ER_NO_SUCH_TABLE: The table name in the query does not exist in the selected database.
- ER_BAD_FIELD_ERROR: One or more column names in the INSERT statement are wrong.
- Access denied: The MySQL username or password in the connection details is incorrect.
- Duplicate entry: A value violates a primary key or unique key constraint.
- Incorrect value count: The number of values does not match the number of columns listed in the query.
For production code, handle errors without exposing database credentials or raw internal messages to end users.
Node.js MySQL INSERT INTO FAQs
How do you write an INSERT query in MySQL?
The basic syntax is INSERT INTO table_name (column1, column2) VALUES (value1, value2);. In Node.js, you pass this query to con.query(). When the values come from variables, use placeholders such as VALUES (?, ?) and pass the values as an array.
How can I insert Node.js variables into a MySQL table?
Use placeholders in the SQL statement and pass the variable values separately. For example, write INSERT INTO students (name, rollno, marks) VALUES (?, ?, ?) and pass [name, rollno, marks] as the second argument to con.query().
How do I insert multiple rows into MySQL from Node.js?
Create an array of rows and use VALUES ? in the INSERT query. Then pass the records array inside another array, as shown in this tutorial: con.query(sql, [records], callback).
How do I get the last inserted row id in Node.js MySQL?
Read result.insertId inside the callback after the INSERT query runs. This is useful when the table has an auto-increment primary key. If the table does not generate an auto-increment value, insertId may be 0.
Can I insert data into MySQL without writing SQL queries in Node.js?
Yes, you can use an ORM or query builder, but the underlying operation is still converted into SQL. This tutorial focuses on direct SQL queries with the mysql module because it clearly shows how INSERT statements work.
QA checklist for Node.js MySQL INSERT INTO tutorial
- Confirm that the database name, table name, and column names match the local MySQL setup.
- Check that new examples use placeholders for variable values instead of string concatenation.
- Verify that single-row and multiple-row INSERT examples explain the shape of the values passed to
con.query(). - Confirm that result object properties such as
affectedRowsandinsertIdare explained with their INSERT-specific meaning. - Run the SQL verification query after the Node.js script to confirm that the rows were inserted.
Conclusion
In this Node.js Tutorial – Node.js MySQL – Node.js MySQL INSERT INTO Query, we have learned to insert one or more records into a table and access properties of the result object. We also saw how to use placeholders for Node.js variables, how to insert multiple rows in a single query, and how to verify inserted data in MySQL.
TutorialKart.com