Nodejs MySQL is getting popular as they mix very well together. Today we will get to know how to setup Nodejs mySQL, connect with database, create db and tables and perform CRUD operation with Nodejs and mySQL.
Introduction
Node.js is one of the most popular open-source, cross-platform backend runtime environment that uses JavaScript. It is mainly used for the purpose of using JavaScript code outside the web browser. Nowadays, Node JS has become popular with mostly NoSQL databases mostly MongoDB. As relational database system like MySQL is popular in the market today we have brought this complete guide on Nodejs MySQL.
You will learn to use Node.js with MySQL database. You will know how you can setup environment, database, tables and also perform CRUD (Create, Read, Update and Delete) operations with Nodejs MySQL.
CHECK OUT THE PART A OF THIS BLOG.
CRUD Operation with Nodejs MySQL
Create
INSERT INTO
" statement.const sql = "INSERT INTO users (name, email) VALUES ('John Watson', 'john@watson.com')";
con.query(sql, (err, result) => { if (err) throw err; console.log("1 record inserted");});
Create Multiple Records
const sql = "INSERT INTO users (name, email) VALUES ? ";const values = [ ["Ben", "ben@gmail.com"], ["Vicky", "vicky@gmail.com"],];con.query(sql, [values], (err, result) => { if (err) throw err; console.log(`${values.length()} records inserted`);});
Read
SELECT
" statement.//Select all the data from users table
const sql = "SELECT * FROM users";
con.query(sql, (err, result) => { if (err) throw err; console.log(result);});
Read particular data
//Select particular data from the users table
const sql = "SELECT name FROM users";
con.query(sql, (err, result) => { if (err) throw err; console.log(result);});
//Here we will get name of all users
Update
UPDATE
" statement.const sql = "UPDATE users SET email = 'new@gmail.com' WHERE name = 'Vicky'";
con.query(sql, (err, result) => { if (err) throw err; console.log("Record Updated");});
Delete
DELETE FROM
" statement.const sql = "DELETE FROM users WHERE name = 'Vicky' ";
con.query(sql, (err, result) => { if (err) throw err; console.log("Record Deleted");});