How to establish a connection to MySQL from Nodejs
How to establish a connection to MySQL from Nodejs

Setup npm

Let’s create a directory with any name to create the app through the terminal.

After creating directory lets begin with npm setup for the package.json file. So enter the details for file creation.

As it created the package.json file. So now we just need to install the MySql package by just a single command in terminal.

The command will install the MySql node Package as well as it will make changes in the package.json file. Here it shows the dependencies and its version number.

SQL Database connection

First import the MySql package in the app file by the require method and also start the MySql localhost server.As we declare the main as app.js so the file must be named as that only.

Now to run the app.js file simply write the command

Database And Table Creation

And Now will create the database as well a table in that particular Database. But first, we will create the database

This will connect database as well as creates the database of name mydb. So run the file as we run earlier i.e $ node app.js.

 

Creating Table

Creating table is as similar as it was creating a database, but all we need to do is to give the database name in the ‘con’ variable. let’s see:

Inserting And Viewing Data

Let us see the further procedure for inserting data and viewing in the terminal. So first we have to insert data into the table.

After the data is inserted successfully, now we can display the data of table on the terminal. So just add the SELECT Query to get the data.

And the data which is displayed are in raw (json format).

Updating And Deleting Data

For Editing the table you just need to change the query. so first we will update the table

And at last for deleting the record or table from the database and that is similar to all above queries.

From :- http://www.geekstrick.com

5 COMMENTS

  1. They experienced hoagies at the yearly FatherSon Barrel Goat Hunt, nonetheless this a single will surly combat it! A mile extended hoogie!

  2. I’m not that much of a online reader to be honest but your blogs really nice, keep it up!

    I’ll go ahead and bookmark your site to come back later.
    All the best

LEAVE A REPLY

Please enter your comment!
Please enter your name here