DEV Community

Cover image for Node.js with MySQL database.
popoola Temitope
popoola Temitope

Posted on

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❤️

Discussion (6)

Collapse
cvicentiu profile image
Vicențiu-Marian Ciorbaru

Great intro! The same tutorial will work for MariaDB, as the protocols are compatible.

Furthermore, one can use npm install mariadb to get the MariaDB connector which is a little bit faster instead.

Collapse
jks92l profile image
SILILO J. KAWANA

Awesome...

Collapse
vladi160 profile image
vladi160

mysql2 is with better performance: github.com/sidorares/node-mysql2/b...

Collapse
drsimplegraffiti profile image
Abayomi Ogunnusi

Thanks for this post

Collapse
demelous profile image
Marcel Nomel

You're the best one

Collapse
prasad2gavande profile image
Prasad • Edited on

I think, using sequelize to work for MySQL will be more helpful.
sequelize.org/