Node.js with MySQL database.

popoolatopzy

popoola Temitope

Posted on August 9, 2021

Node.js with MySQL database.

Connecting node.js project with MySQL database is easy, follow the following steps to connect to the the database

By reading this article I believe you have installed nodee Js on your system and familiar with it.

Step1

Open your code editor.

Step2

Create a new project
Open your command prompt or terminal and enter

 mkdir project_name
 cd project_name
Enter fullscreen mode Exit fullscreen mode

Step3

Create project file.
enter

 npm init -y
Enter fullscreen mode Exit fullscreen mode

into the command prompt or terminal.

Step4

To be able to connect to mysql database you need to install MySQL module into your project.

To do this is very simple, open your CMD or terminal and enter

 npm install mysql
Enter fullscreen mode Exit fullscreen mode

this command will install the module into your project.

Step5

Now we can open connection From our project code to mysql database
add the code below to your app.js code to open a connection.


const mysql = require('mysql');

// Creating a mysql connection
const conn = mysql.createConnection({
   host: "localhost",
   user: "db_username",
   password: "db_password",
   database: "db_name"
});
Enter fullscreen mode Exit fullscreen mode

Step6

Let create a simple database and table

conn.connect((err)=>{
   if (err) throw err;
      console.log("Database connected successful");
   var sql = "CREATE TABLE books (book_name VARCHAR(255), book_description VARCHAR(255))";
   con.query(sql,(err, result)=> {
      if (err) throw err;
         console.log("Table created");
   });
});

Enter fullscreen mode Exit fullscreen mode

You can leave a comment...
Thanks❤️

💖 💪 🙅 🚩
popoolatopzy
popoola Temitope

Posted on August 9, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related