Nodejs, Express mysql always returning ER_BAD_DB_ERROR
Asked Answered
U

6

1

I'm developing a simple web app with Node.js and Express. I have to query a database using mysql module. Every time I try to query the database it shows up this error:

  code: 'ER_BAD_DB_ERROR',
  errno: 1049,
  sqlMessage: "Unknown database 'moneydb'",
  sqlState: '42000',
  fatal: true

I tried to create e a new database but I have always the same error. Wamp is running. credentials are right beacuse if I navigate to localhost/phpmyadmin i log in with root as username and no password.

I post here the relevant code:

app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

index.js

var express = require('express');
var router = express.Router();
var mysql = require('mysql');

// connection setup
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'moneydb'
});


// connect to database
connection.connect((err) => {
    if (err) {
        console.log('Not connected to database');
        throw err;
    } else {
        console.log('Connected to database');
    }
});

// make connection global
global.db = connection;

/*
*  Every page we declare here will be under the index path
*  localhost:3000/ will render home page
*  localhost:3000/disheslist will be under the home page path and will render the disheslist
* */

/* GET home page. */
router.get('/', function (req, res, next) {
    res.render('index', {title: 'Express'});
});

/*GET dish list. */
/*render contains views(pug files)*/
router.get('/dishes', function (req, res, next) {
    let query = "SELECT * FROM `dish` ORDER BY id ASC";

    // execute query
    db.query(query, (err, result) => {
        if (err) {
            // we should redirect to an error page maybe
            res.redirect('/');
        }

        if (result) {
            res.render('dishes', {tableData: result});
        } else {
            res.send("Error");
        }
    });
});

module.exports = router;

dishes.pug

doctype html
html
    head
        title = title
        link(rel='stylesheet', href='/stylesheets/style.css')
    body
    table
        thead
            tr
            th id
            th name
            tbody

What's wrong? Thank you!

Unaccompanied answered 29/2, 2020 at 13:3 Comment(4)
your server says there is no database with that name so check, eventually a typoTranscurrent
No typo. I created another database, copied and pasted the name from the database into the code, and I have the same error, I think it' s something else, but I don' t know what.Unaccompanied
enable the logs of mysql and see what reaches the server also check error log and log if there are events in the system logTranscurrent
You mean mysql on the server where I created the database or the mysql Nodejs module?Unaccompanied
U
2

Problem solved.

I checked which port was used from MySql on wamp and I found the 3308 port. I added the port to the configuration before connecting in the index.js and I got it. Code updated here:

index.js

var express = require('express');
var router = express.Router();
var mysql = require('mysql');

// connection setup
const connection = mysql.createConnection({
    host: 'localhost',
    port: 3308,
    user: 'root',
    password: '',
    database: 'dbname'
});


// connect to database
connection.connect((err) => {
    if (err) {
        console.log('Not connected to database');
        throw err;
    } else {
        console.log('Connected to database');
    }
});

// make connection global
global.db = connection;

/*
*  Every page we declare here will be under the index path
*  localhost:3000/ will render home page
*  localhost:3000/disheslist will be under the home page path and will render the disheslist
* */

/* GET home page. */
router.get('/', function (req, res, next) {
    res.render('index', {title: 'Express'});
});

/*GET dish list. */
/*render contains views(pug files)*/
router.get('/dishes', function (req, res, next) {
    let query = "SELECT * FROM `dish` ORDER BY id ASC";

    // execute query
    db.query(query, (err, result) => {
        if (err) {
            // we should redirect to an error page maybe
            res.redirect('/');
        }

        if (result) {
            res.render('dishes', {tableData: result});
        } else {
            res.send("Error");
        }
    });
});

module.exports = router;

Thank you all!

Unaccompanied answered 29/2, 2020 at 15:12 Comment(0)
E
0

Looks like user do not have permission on database server. Looking at the error message seems like request is able to reach server however due to insufficient privileges an error is returned by the server.

Etherege answered 29/2, 2020 at 13:33 Comment(1)
What kind of privileges? Where I should check?Unaccompanied
T
0

I commented/took the database: '<DB NAME>' out of the object.

const connection = mysql.createConnection({
  user : 'root',
  host : '127.0.0.1',
  //database : '<db name>',
  port: '3306',
  password : '<your password>'
});
Tithable answered 6/1, 2022 at 21:20 Comment(1)
Please add an explanation for your answerAntibody
L
0

problem solved - changed port number. mysql db port is 3360 and in index.js port should be 3360.

await createConnection({
  host: "localhost",
    type: "mysql",
    port: 3360,
    database: "graphqlschema1",
    username: "root",
    password: "sksuman",
    logging: true,
    synchronize: false,
    entities: [],
  });
Lemma answered 27/2, 2022 at 10:45 Comment(0)
A
0

In mac I navigated to /Applications/MAMP/bin/phpMyAdmin/config.inc.php

And found that my username was "root" and password was also "root"

$cfg['Servers'][$i]['user']          = 'root';      
$cfg['Servers'][$i]['password']      = 'root';
Adhere answered 27/2 at 10:31 Comment(0)
I
-1

Go to terminal in ubuntu in MySQL. Create a database:

CREATE DATABASE yourdatabasename

It will resolve your issue.

If answered 15/9, 2022 at 7:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.