Node Js:MYSQL没有连接

时间:2016-10-14 07:09:02

标签: mysql node.js

我是node.js的新手,所以我陷入了困境。我试图从这些网站Code MentorGithub

中学习它

直到现在我已经这样做了:

var mysql = require('mysql');

var app = express();

// Database operations
var connection = mysql.createConnection({
  host : 'localhost',
  port : '8888',
  user : 'sharad',
  password : 'teks',
  dbName : 'FirstDataBase'
});

connection.connect(function (error) {
  if (error){
    console.error('error connecting :' + error.stack);
    return;
  }
  console.log('Connected as id :'+ connection.threadId);
});

app.get("/",function(request,response){
  console.log(' saving');
  var post  = {from:'me', to:'you', msg:'hi'};
  connection.query('INSERT INTO FirstDataBase SET ?', post, function(err, result) {
    if (err) throw err;
  });
});

app.get("/",function(request,response){
  connection.query('SELECT * from FirstDataBase', function(err, rows, fields) {
    connection.end();
    if (!err)
      console.log('The solution is: ', rows);
    else
      console.log('Error while performing Query.');
  });
});

app.listen(8888);

我看不到我在代码中打印的任何日志。任何帮助,将不胜感激。感谢

编辑:

如果删除最后一行app.listen(8888);

,我会收到错误
error connecting :Error: connect ECONNREFUSED 127.0.0.1:8888
    at Object.exports._errnoException (util.js:907:11)
    at exports._exceptionWithHostPort (util.js:930:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1077:14)
    --------------------
    at Protocol._enqueue (/Users/Admin/IdeaProjects/FirstNodeJS/node_modules/mysql/lib/protocol/Protocol.js:141:48)
    at Protocol.handshake (/Users/Admin/IdeaProjects/FirstNodeJS/node_modules/mysql/lib/protocol/Protocol.js:52:41)
    at Connection.connect (/Users/Admin/IdeaProjects/FirstNodeJS/node_modules/mysql/lib/Connection.js:136:18)
    at Object.<anonymous> (/Users/Admin/IdeaProjects/FirstNodeJS/app.js:40:12)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at startup (node.js:139:18)

3 个答案:

答案 0 :(得分:1)

我通过安装MAMP并使用MAMP提供的字段解决了我的问题。

MAMP fields

Updated code

答案 1 :(得分:1)

我这样解决了这个问题

安装mysql:

npm安装mysql

var mysql = require('mysql');

let connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    port: '8888',  /* port on which phpmyadmin run */
    password: 'root',
    database: 'dbname',
    socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock' //for mac and linux
});

connection.connect(function(err) {
    if (err) {
      return console.error('error: ' + err.message);
    }

    console.log('Connected to the MySQL server.');
  });

答案 2 :(得分:0)

试试这个

var connection = mysql.createConnection({
 host     : 'localhost',
 user     : 'xxxxx',
 password : 'xxxxx',
 database : 'xxx'
 });
connection.connect();