node.js不会连接到mysql

时间:2018-04-12 01:44:23

标签: javascript mysql node.js

代码:

var mysql = require('mysql');
var db_config = require('./db-config.json');

var connection = mysql.createConnection({
  host: db_config.host,
  user: db_config.user,
  port: db_config.port,
  password: db_config.password,
  database: db_config.database
});

connection.connect(function(err){
  if (!err) {
    console.log("Database is connected... \n\n");
  } else {
    console.log("Error connecting database \n\n" + err);
  }
});

connection.query('select 1+1 as solution', function(err, rows, fields){
  if(err) throw err;
  console.log('The solution is: ', rows[0].solution);

});

connection.end();

和我的./db-config.json是

{
"host": "**.*.**.***",
"user": "***",
"port": "13306",
"password": "****",
"database": "***"
}

并且错误是     连接数据库时出错

Error: Connection lost: The server closed the connection.
C:\project\Nodejs\my-app\routes\db\dbtest.js:21
if(err) throw err;
^

Error: Connection lost: The server closed the connection.
at Protocol.end            (C:\project\Nodejs\node_modules\mysql\lib\protocol\Protocol.js:113:13)
at Socket.<anonymous>    (C:\project\Nodejs\node_modules\mysql\lib\Connection.js:109:28)
at emitNone (events.js:111:20)
at Socket.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1055:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
--------------------
at Protocol._enqueue    (C:\project\Nodejs\node_modules\mysql\lib\protocol\Protocol.js:145:48)
at Protocol.handshake    (C:\project\Nodejs\node_modules\mysql\lib\protocol\Protocol.js:52:23)
at Connection.connect (C:\project\Nodejs\node_modules\mysql\lib\Connection.js:130:18)
at Object.<anonymous> (C:\project\Nodejs\my-app\routes\db\dbtest.js:12:12)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)

这很奇怪,因为这个数据库已经在另一个程序中使用了,它的工作正常。 我认为代码本身就是问题,因为我的本地mysql没有问题。

我刚开始学习nodejs&amp;表达并坚持在这个非常基本的阶段。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

在回调完成工作之前,您正在结束与数据库的连接。

var mysql = require('mysql');
var db_config = require('./db-config.json');

var connection = mysql.createConnection({
  host: db_config.host,
  user: db_config.user,
  port: db_config.port,
  password: db_config.password,
  database: db_config.database
});

connection.connect(function(err){
  if (err) {
    console.log("Error connecting database \n\n" + err);
    throw err
  } 
  connection.query('select 1+1 as solution', function(err, rows, fields){
    if(err) throw err;
    console.log('The solution is: ', rows[0].solution);
    connection.end();
    });
});

回调不会立即执行,它们是异步的。在完成所有异步操作之前,您的代码将进入connection.end()。