skip to Main Content

I’m trying to connect to MySQL via nodeJS app using express for server, ive read the mysql npm documentation in order to begin connection but it seems like i get the error from the callback function i wrote inside createConnection.connect() and im using phpmyadmin just to see results and charts

here is my code:

const express = require('express');
const app = express();
const mysql = require('mysql'); 
require('dotenv').config();
const workers = require('./routes/workers');


app.use('/', workers);


const DB = mysql.createConnection({
    host     : 'localhost',
   user     : 'root',
  charset: 'utf8_general_ci',
  password: '',

});

DB.connect((err) => {
     throw `error: ${err}`
 });

 app.listen(process.env._PORT, () => {
     console.log(`Server is running on ${process.env._PORT}`);
 });

2

Answers


  1. Install sequelizejs , mysql ,mysql2 libararies

    var Sequelize = require('sequelize');
    var sequelize = new Sequelize(dbName, username, password,{ host: localhost,
        // data type
        dialect: mysql,
    });
    

    You can use the .authenticate() function to test if the connection is OK:

    try {
      await sequelize.authenticate();
      console.log('Connection has been established successfully.');
    } catch (error) {
      console.error('Unable to connect to the database:', error);
    }
    
    Login or Signup to reply.
  2. You are not checking error after connection. You have to check is there any error while database connection like following.

    DB.connect((err) => {
         if(err){
            throw `error: ${err}`       
         }
         console.log("Database connected successfully");
     });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search