gpt4 book ai didi

mysql - 从数据库获取响应作为数组而不是单独的对象

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

我想从数据库回调函数获取响应作为数组,而不是单独的对象。问题是,在当前设置下,Express 会抛出“ header 已设置”错误。

我认为问题出在数据库回调函数中:

文件:database_connection.js

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();
}
}
if (conn) {
var q = conn.query.apply(conn, queryArgs);
q.on('end', function () {
conn.release();
});
console.log(events);
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;
}
};
}};

我这样使用它:

文件:database_operations.js

exports.streepjes = function(){
return {
getByUserID: function(userid, callback_streepjes){
sqlSelect = sqlQuery.select();
//QUERY:
let command = sqlSelect.from('steepjes').select('*').where({USERID: userid}).build();
database.connection.query(command).on('result', function(result){
console.log("ANOTHER ONE");
console.log(result);
return callback_streepjes(result);
}).on('error', function(err){
console.error(err);
});
}
}
};

我在快速路由器功能中使用这些功能:

router.get('/getStrepenByUserID', function(req, res) {
database_operations.streepjes().getByUserID(req.query.userid, function(response){
res.json(response);
});
});

这种方法的问题是路由中的回调函数被多次调用。这会创建 header 已设置错误。

明确的问题:

我想更改数据库连接函数,使其以一个字符串返回所有输出,而不是在每个数据库条目上调用回调函数。但我就是不知道该怎么做。也许有人可以提示如何解决这个问题?

提前致谢!

编辑:

我使用 MySQL,当您只获取一项时,这些函数可以正常工作,当它响应多个行数据包时,它会崩溃

临时答案:

看我的回答

最佳答案

通过将database_operations中的函数更改为:

exports.streepjes = function(){
return {
getByUserID: function(userid, callback_streepjes){
sqlSelect = sqlQuery.select();
//QUERY:
let command = sqlSelect.from('steepjes').select('*').where({USERID: userid}).build();
let output = [];
database.connection.query(command).on('result', function(result){
output.push(result);
}).on('error', function(err){
console.error(err);
}).on('end', function(){
return callback_streepjes(output);
});
}
}
};

基本上将每个元素推送到称为输出的数组上,然后仅在“结束”事件触发后返回它。如果有更好的解决方法,请告诉我!

关于mysql - 从数据库获取响应作为数组而不是单独的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54785112/

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