0

I've tried to implement this code and terminal throws error something like this stucked in it As I've applied this code but it throws the error "Access denied for user ''@'localhost' to database 'mydb'"

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "myusername",
  password: "mypassword"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  /*Create a database named "mydb":*/
  con.query("CREATE DATABASE mydb", function (err, result) {
    if (err) throw err;
    console.log("Database created");
  });
});
8
  • see if you can access mysql from terminal Commented Apr 17, 2019 at 6:35
  • as I have got the Connected message on console but can't able to create database from that code Commented Apr 17, 2019 at 6:37
  • could you try only .connect without the con.query? Commented Apr 17, 2019 at 6:43
  • Yess, it's working without con.query Commented Apr 17, 2019 at 6:46
  • well there you go, you could move your con.query() outside Commented Apr 17, 2019 at 6:57

1 Answer 1

1

create a config folder and create a file databaseConfig.js

var mysql = require('mysql');

config = {
  host: 'localhost',
  user: 'root',
  password: '',
  database: '<DB name>'
}
var connection =mysql.createConnection(config); //added the line
connection.connect(function(err){
if (err){
   console.log('error connecting:' + err.stack);
}
   console.log('connected successfully to DB.');
});

module.exports ={
   connection : mysql.createConnection(config) 
} 

create a app.js file

var express = require('express');
var cors = require('cors');
app = express(),
app.use(cors()),
port = process.env.PORT || 3001;
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./api/routes/routes'); //importing route
routes(app);
console.log('todo list RESTful API server started on: ' + port);
app.listen(port);

create a controller.js file

var config = require('../../databaseConfig.js');
var connection= config.connection
connection.query ('CREATE DATABASE mydb', function(error, results){
  if (results){
     console.log(results);
  }  
  else{
     console.log(error);
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

This answer has nothing to do with access denied

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.