SQL uses following INSERT statement to insert data in tables.
1 |
Insert Single Record
Create a JavaScript file in your application to insert data to table using Node.js application.
vim insert_mysql_data.js
Add the following content.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | var mysql = require('mysql'); var dbconn = mysql.createConnection({ host: "localhost", port: "3306", user: "root", password: "secret", database: "tecadmin" }); dbconn.connect(function(err) { if (err) throw err; console.log("Database connected successfully!"); var sqlquery = "INSERT INTO users (user_id, user_name, email) VALUES (1, 'john', '[email protected]')"; dbconn.query(sqlquery, function (err, result) { if (err) throw err; console.log(result.affectedRows + " record inserted"); }); }); |
Execute the JavaScript file using node. On successful execution you will get results like below.
node insert_mysql_data.js Output: Database connected successfully! 1 record inserted
Insert Multiple Records
You can also insert multiple records into the database table. Create a JavaScript file in your application to insert data to table using Node.js application.
vim insert_multi_record_mysql.js
Add the following content. We have created an array of records then inserted into the database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | var mysql = require('mysql'); var dbconn = mysql.createConnection({ host: "localhost", port: "3306", user: "root", password: "secret", database: "tecadmin" }); dbconn.connect(function(err) { if (err) throw err; console.log("Database connected successfully!"); var sqlquery = "INSERT INTO users (user_id, user_name, email) VALUES ?"; records = [ ]; dbconn.query(sqlquery, [records] , function (err, result) { if (err) throw err; console.log(result.affectedRows + " record inserted"); }); }); |
Execute the JavaScript file using node. On successful execution you will get results like below.
node insert_multi_record_mysql.js Output: Database connected successfully! 4 record inserted