Skip to main content

Database connection

1. Let's start by creating an index.js then initializing your JavaScript project by running npm init in your terminal after that let's download the libraries that we will be using today which are express and mysql by running npm install express mysql2.Screenshot 2024-04-23 132412.png

2. Create 3 directory which are routersControllersservices then create 2 directory transactions and users
Screenshot 2024-04-24 150123.png

3. Write the following code in the index.js

const express = require("express");
const app = express();
const port = 5000;
app.use(express.json());


app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

4. In directory services create database.js

5. Import the mysql library to your project.

const mysql = require("mysql2");

6. Add the following code

  • This is the database configuration of your database.
const connection = mysql.createConnection({
  host: "tutorialdb.pspgun.com",
  port: "13308",
  user: "",
  password: "",
  database: "csc-105",
});

      7. Connect to the database

      • This line of code is using the connection variable from above to connect to the database using .connect() method.
      connection.connect((err) => {
        if (err) {
          console.log(err);
        } else {
          console.log("Database is connected");
        }
      });

      8. Export the connection so that we can use it in other file.

      module.exports = connection;

      The code right now should look like this in 

      const mysql = require("mysql2");
      
      const connection = mysql.createConnection({
      	host: "tutorialdb.pspgun.com",
      	port: "13308",
      	user: "mentor",
      	password: "mentor1212312121",
      	database: "csc-105",
      });
      
      // Connect to database
      connection.connect((err) => {
      	if (err) {
      		console.log(err);
      		throw "Database is not connected";
      	} else {
      		console.log("Database is connected");
      	}
      });
      
      module.exports = connection;
      

      9. Restart the application

      • If your database connection is invalid, it will show you an error. ❌👇🏻

      • If your database connection is valid, your application will run correctly. ✅👇🏻

      Screenshot 2024-04-23 134128.png

      -----------------------------------------------------------End of Database connection------------------------------------------------------