我正在使用 Node JS 服务器和 firebird 数据库开发 Cordova 应用程序。 这两个数据库存在,我可以通过 isql-fb 连接到它。
当我通过电话创建第一个连接时,该连接以及在此连接上完成的查询都有效。
但是,当我创建第二个连接时,它不起作用。
这是我的代码:
连接表,将连接重新分组为 ["username", connexion] 表
var connectionTable = [];
连接到数据库并在 connectionTable 中添加连接的函数:
function connectionToDB(username, password, dbAddress){
var con = fb.createConnection();
con.connectSync(dbAddress, username, password, '');
var newConnection = [username, con];
connectionTable.push(newConnection);
console.log('connection finished'); //it is displayed for both connections so I think it works
};
通过输入的用户名返回所需连接的函数:
function getConnection(username){
for(x in connectionTable){
if(connectionTable[x][0]==username) {
return connectionTable[x][1];
}
else {console.log("No connection found with username : " + username); return 0;}
}
};
然后,在我的 Node JS 服务器上,我有这个“路线”:
app.get('/checkAccount/:username', function(req, res){
console.log("checkAccount avant body");
console.log(req.params);
var usernameAsking = req.params.username;
console.log("usernameAsking = " + usernameAsking); //returns username in both cases
var connexionLinked = getConnection(usernameAsking);
console.log(typeof connexionLinked);
console.log(connexionLinked);
if(connexionLinked == 0) console.log("Problem. No linked connexion found");
else console.log("connexion found");
var query = connexionLinked.querySync("SELECT * from shops");
var rows = query.fetchSync('all', true);
console.log(sys.inspect(rows));
var shopNameString = JSON.stringify(rows);
console.log("string : " + shopNameString);
res.send(shopNameString);
});
因此,对于与数据库的第一次连接,它工作得很好,并且确实向我返回了它的数据库的值。
但是,它不适用于第二个不同的连接,它说它等于 0,所以我假设它没有在 GetConnection 中找到它。
我不明白为什么它适用于一个而不适用于另一个...我之前也尝试连接到几个不同的连接,而不是这个过程并且它有效。所以问题不在于我们不能在同一个 NodeJS 服务器上建立多个连接,而是在这种情况下,我们显然找不到好的连接......
有人知道我做错了什么吗?
非常感谢任何帮助,谢谢。
-- 编辑 --
连接以这种方式工作。错误出现在 getConnection(username) 的 for 循环中。如果有人试图做一个连接表,我会把这篇文章放在这里。
谢谢大家
最佳答案
我发现了问题。我觉得我好笨。但现在我们知道连接的创建是这样进行的。 这是没有人会犯的最尴尬的错误:
function getConnection(username){
for(x in connectionTable){
console.log("connectionTable : " + connectionTable[x]);
console.log("connectionTable FULL: " + connectionTable);
console.log("connectionTable[x][0] : " + connectionTable[x][0]);
console.log(connectionTable.length);
if(connectionTable[x][0]==username) {
return connectionTable[x][1];
}
}
console.log("No connection found with username : " + username);
return 0; // Error solved : The return was not supposed to be in the for loop
//it was only checking the first username value.
};
感谢大家的宝贵时间和帮助:)
关于javascript - 连接已创建但未找到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45481595/