In this tutorial you will learn about the Nodejs MySQL Insert Records and its application with practical example.
Node.js MySQL Insert Records
A record can be inserted into MySQL Table simply by using “INSERT INTO” statement.
Example :- Let’s insert a record in “employees” table under “nodemysql” database.
Step 1:- Let’s, create a node_mysql_insert_tbl.js file and put the following code in it –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
var mysql = require('mysql'); var con = mysql.createConnection({ host: "localhost", user: "root", password: "", database: "nodemysql" }); con.connect(function(err) { if (err) throw err; console.log("Connected!"); var sql = "INSERT INTO employees (emp_name, emp_age, emp_salary) VALUES ('John Doe', '27', '5000')"; con.query(sql, function (err, result) { if (err) throw err; console.log("W3Adda | Single record inserted."); }); }); |
Step 2:- Save the code and open the terminal again, and type the following command in order to run the file.
1 |
$ node node_mysql_insert_tbl.js |
you will see following output on terminal –
Insert Multiple Records
Step 1:- Let’s, create a node_mysql_multi_insert_tbl.js file and put the following code in it –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
var mysql = require('mysql'); var con = mysql.createConnection({ host: "localhost", user: "root", password: "", database: "nodemysql" }); con.connect(function(err) { if (err) throw err; console.log("Connected!"); var sql = "INSERT INTO employees (emp_name, emp_age, emp_salary) VALUES ?"; var values = [ ['Keith', '28', '5000'], ['Alex', '30', '8000'], ['Murphy', '35', '10000'], ['Amanda', '25', '5000'], ['Jason', '25', '5000'], ]; con.query(sql, [values], function (err, result) { if (err) throw err; console.log("W3Adda | MySQL Multiple Record Inserted"); console.log("No. of records inserted- " + result.affectedRows); }); }); |
Step 2:- Save the code and open the terminal again, and type the following command in order to run the file.
1 |
$ node node_mysql_multi_insert_tbl.js |
you will see following output on terminal –