gpt4 book ai didi

mysql - Node.js MySQL 连接未连接但未显示错误

转载 作者:行者123 更新时间:2023-11-29 05:57:20 25 4
gpt4 key购买 nike

我是 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 更改超时。


第二种可能性是它实际上连接了,因为你没有 console.log 告诉你你不知道。请引用我之前向您描述的异步问题。

关于mysql - Node.js MySQL 连接未连接但未显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48192495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com