Node.js Database Connection and Select Query

Posted at: March 18, 2019 4:37 PM

How to connect MySQL database in Node.js

In this lesson we will learn, how to connect MySQL database in the Node.js and will fetch records from database using select query using express framework.

For creating a nodejs application, you can see my previous lesson How to handle GET and POST requests in Node js

Before use mysql in Node.js must be ensured MySQL Database should be installed in your machine. You can see Installing MySQL documentation.

Install mysql node modules in node.js

Install mysql node modules in your application.

Create a Custom Module for Database Connection

Create a db.js file in the root folder for database connection and use this connection in your entire project.

Connect your database using your MySQL database credential host, database user, database password and database name.

MySQL SELECT query

Create a file routes/products.js and import var db = require('../db'); into this for database connection.

Use MySQL select query for fetching all the records.

Fetch Single Record

For fetch single record using rows[0].

View File

Create a file views/products.hbs

Edit app.js

Edit app.js file and import var productsRouter = require('./routes/products'); and set products route app.use('/products', productsRouter);

Complete code of app.js

Integrate Bootstrap

If you want to use bootstrap in your application, then copy Bootstrap CDN link in the views/layout.hbs

MySQL Database Tables

Table products

Conclusion

In this lesson we have learned integration mysql database in the Node.js and use a MySQL select query for fetching the records. And also integrate bootstrap.

You can watch video on Node.js Database Connection and Select Query


mysqlselect querybootstrapdatabase connection

Please leave comments

1 Comments

truecodex launched free android app. You can download and install truecodex app on your mobile and get notification of the latest post.

Video Tutorials on YouTube