Nodejs Mysql insert query

to create the MySQL insert query in Nodejs, I have defined 2 steps

Insert Single Record into the table

Step:1) firstly create the connection.js file.


const mysql = require('mysql');
const config  = {
  connectionLimit : 10,
  host     : 'localhost', // Database hostname, 
  user     : 'root', // Database Username
  password : 'jnnn23nn', // Database Password,
  database : 'dbname', //Database Name
};

const pool = mysql.createPool(config);
// Export the pool
module.exports = pool;

IN the connection.js file, You have to include mysql package and create the connection pool.

Step:2) Now, create the insert.js file and include the connection.js file and write the insert query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('insert into users(name,age) values(?,?)',['John',35], function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the insert.js file.


node insert.js
Output:-
OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 1,
serverStatus: 2,
warningCount: 0,
message: ”,
protocol41: true,
changedRows: 0 }

IN this file, I have created an insert query to save records in the users table.

Now, get the results from the table


select * from users
ID
Name
Age
1
John
35

Insert Multiple Records into the table

Step:2) Now, create the insert.js file and include the connection.js file and write the insert query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('insert into users(name,age) values ?',[[['Rom',31],['Mathew',32],['Sachin',38]]], function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the insert.js file.


node insert.js
Output:-
OkPacket {
fieldCount: 0,
affectedRows: 3,
insertId: 2,
serverStatus: 2,
warningCount: 0,
message: ‘&Records: 3 Duplicates: 0 Warnings: 0’,
protocol41: true,
changedRows: 0 }

Now, get the results from the table


select * from users
Output:-
ID
Name
Age
1
John
35
2
Rom
31
3
Mathew
32
4
Sachin
38