Node js MySQL Insert Query Example

In this post, we will see how to insert a record into MySQL database using Node js.

Setup MySQL database

Make sure that you have installed the MySQL database in your machine.
Use the following command to create a database:
create database demo;
Use below SQL script to create todos table in 'demo' database:
CREATE TABLE `todos` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `description` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;

Install MySQL Driver

To download and install the "mysql" module, open the Command Terminal and execute the following:
$npm install mysql --save
Now you have downloaded and installed a MySQL database driver.
Node.js can use this module to manipulate the MySQL database:
var mysql = require('mysql');

Node js MySQL Insert Query Example

Let's create a file named 'insert-record.js' and add the following code to it:
const mysql = require('mysql');
// connection configurations
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'demo'
});

// connect to database
connection.connect(function (err) {
    if (err) throw err
    console.log('You are now connected with mysql database...')
});

let params = {
    name: "Todo 1",
    description: "Todo 1 description"
}

connection.query("INSERT INTO todos SET ? ", params,
    function (error, results, fields) {
        if (error) throw error;
        console.log("Record inserted");
    });
Run above code with the following command:
$ node .\insert-record.js
You are now connected with mysql database...
Record inserted

References



Comments