我是Node的新手,刚使用了一个多星期,一切都很好,直到我尝试连接到MySQL数据库,我没有运气。
我已经安装了必要的文件;
npm install mysql
我的代码如下;
const mySQL = require('mysql');
const mySQLCon = mySQL.createConnection({
host: "localhost",
user: "username",
password: "password",
database: "databaseName"
});
function connectTest() {
mySQLCon.connect(function(err) {
if(err){
console.log(err.code);
console.log(err.fatal);
}
});
console.log(mySQLCon.state);
sSQL = "SELECT sField FROM tblName WHERE iID = 1";
mySQLCon.query(sSQL, function(err, rows, fields) {
if(err){
console.log("An error ocurred performing the query.");
return;
}
if (rows.length > 0) {
console.log(rows[0].sField);
} else {
console.log("No Records found!");
}
});
mySQLCon.end(function(){
// The connection has been closed
});
}
connectTest()
我在用;
console.log(mySQLCon.state);
查看连接的状态并显示“已断开连接”。
我没有任何错误,当这运行它只是没有做任何事情。
数据库位于远程PC上,但是我使用相同的凭据从该计算机以其他方式成功地连接到数据库而没有任何问题(navicat)。
我试着在本地数据库计算机上运行代码,看看是不是这个问题,它做了同样的事情,没有连接,没有错误。
任何帮助都将不胜感激,因为我完全迷失了,没有任何错误来指导我,我正在做我认为是正确的!
谢谢
最佳答案
有两种可能性。
首先,连接是异步的,您应该等待连接显式结束后再执行其他操作。
例子:
mySQLCon.connect(function(err) {
if(err){
console.log(err.code);
console.log(err.fatal);
return;
}
console.log(mySQLCon.state);
sSQL = "SELECT sField FROM tblName WHERE iID = 1";
mySQLCon.query(sSQL, function(err, rows, fields) {
if(err){
console.log("An error ocurred performing the query.");
return;
}
if (rows.length > 0) {
console.log(rows[0].sField);
} else {
console.log("No Records found!");
}
});
mySQLCon.end(function(){
// The connection has been closed
});
});
因此,第一种可能是永远不会出现任何错误,因为连接有超时。所以直到时间到了函数才会挂起。
似乎可以使用
connectTimeout: 1000000
选项更改超时。第二种可能性是它实际上是连接的,因为你没有告诉你你不知道。我指的是刚才我向您描述的异步问题。
关于mysql - Node.js MySQL连接未连接,但未显示任何错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48192495/