连接到数据库并在Node中创建数据库

时间:2019-04-17 05:51:17

标签: mysql node.js

I've tried to implement this code and terminal throws error something like this stucked in it 在应用此代码后,它引发了错误 “拒绝用户'@'localhost'访问数据库'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");
  });
});

1 个答案:

答案 0 :(得分:0)

  

创建一个配置文件夹并创建一个文件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) 
} 
  

创建一个app.js文件

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);
  

创建一个controller.js文件

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);
  }
});