How to Insert Data into MySQL Database Using Node JS

How to Insert Data into MySQL Database Using Node JS

Here you will learn how to Insert Data into MySQL Database Using Node JS. To Insert Data Into MySQL Database we will use the mysql2 module.

But, before going further, I suggest you first check out this – How to Query a MySQL Database Using Node JS.


Database Configuration

Database Nametest
Table Nameusers

So first, Strat your MySQL Server and create a Database called test, and then inside the test database create a table called users.

Use the following SQL Code to create users table and the structure of the users table.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
 `age` int(11) NOT NULL,
 `email` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Database Connection

How to create Node JS MySQL Database Connection using the mysql2 module.


const mysql = require('mysql2');
const db_connection = mysql.createPool({
    host: 'localhost',
    user: 'root',
    database: 'test',
    password:'your_db_password'
});

Insert Data Into MySQL Database


let _name = 'John Doe';
let _age = 21;
let _email = '[email protected]';

db_connection.promise()
.execute("INSERT INTO `users`(`name`,`age`,`email`) VALUES(?, ?, ?)",[_name, _age, _email])
.then(([result]) => {
    // console.log(result);
    if(result.affectedRows === 1){
        console.log("User Inserted");
    }
}).catch(err => {
    console.log(err);
});

Full Code of Inserting Data


const mysql = require('mysql2');
const db_connection = mysql.createPool({
    host: 'localhost',
    user: 'root',
    database: 'test',
    password:'your_db_password'
});

let _name = 'John Doe';
let _age = 21;
let _email = '[email protected]';

db_connection.promise()
.execute("INSERT INTO `users`(`name`,`age`,`email`) VALUES(?, ?, ?)",[_name, _age, _email])
.then(([result]) => {
    // console.log(result);
    if(result.affectedRows === 1){
        console.log("User Inserted");
    }
}).catch(err => {
    console.log(err);
});

Leave a Reply

Your email address will not be published. Required fields are marked *