我正在尝试将Mysql DB与节点js连接,但出现以下错误。
Error: Connection lost: The server closed the connection.
at Protocol.end (node_modules\mysql\lib\protocol\Protocol.js:112:13)
at Socket.<anonymous> (\node_modules\mysql\lib\Connection.js:94:28)
at Socket.<anonymous> (\node_modules\mysql\lib\Connection.js:526:10)
at Socket.emit (events.js:322:22)
at endReadableNT (_stream_readable.js:1187:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
我创建了一个单独的文件来配置数据库。下面显示了db.js
var mysql = require('mysql');
var pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'root',
database: 'tms',
connectionLimit: 10,
multipleStatements: true,
port: 5000,
connectionLimit: 1000,
connectTimeout: 60 * 60 * 1000,
acquireTimeout: 60 * 60 * 1000,
timeout: 60 * 60 * 1000
});
exports.connection = {
query: function () {
var queryArgs = Array.prototype.slice.call(arguments),
events = [],
eventNameIndex = {};
pool.getConnection(function (err, conn) {
if (err) {
if (eventNameIndex.error) {
eventNameIndex.error(err);
}
}
if (conn) {
var q = conn.query.apply(conn, queryArgs);
q.on('end', function () {
conn.release();
});
events.forEach(function (args) {
q.on.apply(q, args);
});
}
});
return {
on: function (eventName, callback) {
events.push(Array.prototype.slice.call(arguments));
eventNameIndex[eventName] = callback;
return this;
}
};
}
};
我正在尝试从这样的路由查询数据。
const express = require('express');
const Database = require('../../database/db.js');
const sql = require('../../database/sql.js');
const router = express.Router();
const config = {};
const bcrypt = require('bcrypt');
//var database = new Database;
router.post('/', (req, res) => {
let someRows;
let procedure = sql.registerUser;
let hashPwd = bcrypt.hashSync(req.body.userReg.pwd, 10);
let requestArgs = [];
requestArgs[0] = req.body.userReg.firstName;
requestArgs[1] = req.body.userReg.lastName;
requestArgs[2] = req.body.userReg.email;
requestArgs[3] = hashPwd;
requestArgs[4] = req.body.userReg.userId;
//debugger;
console.log("b4 connt");
Database.connection.query(procedure, requestArgs)
.on('result', function (row) {
//setData(row);
console.log("in resltt");
res.send(row)
})
.on('error', function (err) {
console.log("in err :: " + err);
res.send(err);
//callback({error: true, err: err});
});
});
module.exports = router;
我正在尝试学习数据库连接,这是我的第一次尝试。我试图找到一种解决方案,但并非所有人都能得到。 请帮助...预先感谢。