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 dotenv.

Screenshot 2024-04-23 132412.png

2. Create 3 directory which are routersControllersservices and create .env file then create 2 directory transactions and users
Screenshot 2024-04-25 142019.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 .env write down the text below

host = "csproject.sit.kmutt.ac.th"
port = "3306"
user = "your own username"
password = "your own password"
database = "your schema name"
//USe username, password that was send to your email

5. In directory services create database.js

6. Import the mysql and dotenv library to your project and config the dotenv.

const mysql = require("mysql2");
const dotenv = require("dotenv");

dotenv.config();

7. Add the following code

  • This is the database configuration of your database.
const connection = mysql.createConnection({
	host: process.env.host,
	port: process.env.port,
	user: process.env.user,
	password: process.env.password,
    database: process.env.database,
});

      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 dotenv = require("dotenv");
      //make the file know that we will be using .env
      dotenv.config();
      
      const connection = mysql.createConnection({
      	host: process.env.host,
      	port: process.env.port,
      	user: process.env.user,
      	password: process.env.password,
        	database: process.env.database,
      });
      
      // 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-