MySQL 如何访问 RowDataPacket 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31221980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access a RowDataPacket object
提问by paK0
I'm currently developing a desktop application with Node-webkit. During that process I need to get some data from a local MySQL-database.
我目前正在使用 Node-webkit 开发桌面应用程序。在这个过程中,我需要从本地 MySQL 数据库中获取一些数据。
The querying works fine, but I can't figure out how to access the results. I store all of them in an array that is then passed to a function. In the console they look like this:
查询工作正常,但我不知道如何访问结果。我将它们全部存储在一个数组中,然后传递给一个函数。在控制台中,它们看起来像这样:
RowDataPacket {user_id: 101, ActionsPerformed: 20}
RowDataPacket {user_id: 102, ActionsPerformed: 110}
RowDataPacket {user_id: 104, ActionsPerformed: 3}
And here is the query structure:
这是查询结构:
var ret = [];
conn.query(SQLquery, function(err, rows, fields) {
if (err)
alert("...");
else {
for (var i of rows)
ret.push(i);
}
doStuffwithTheResult(ret);
}
How do I retrieve this in the doStuffwithTheResult
function? The values are more important, but if I could get the keys as well that would be great.
如何在doStuffwithTheResult
函数中检索它?值更重要,但如果我也能拿到钥匙那就太好了。
回答by paK0
Turns out they are normal objects and you can access them through user_id
.
原来它们是普通对象,您可以通过user_id
.
RowDataPacket is actually the name of the constructor function that creates an object, it would look like this new RowDataPacket(user_id, ...)
. You can check by accessing its name [0].constructor.name
RowDataPacket 实际上是创建对象的构造函数的名称,它看起来像这样 new RowDataPacket(user_id, ...)
。您可以通过访问其名称进行检查[0].constructor.name
If the result is an array, you would have to use [0].user_id
.
如果结果是一个数组,则必须使用[0].user_id
.
回答by user5545457
I also met the same problem recently, when I use waterline in express project for complex queries ,use the SQL statement to query.
我最近也遇到了同样的问题,在express项目中使用waterline进行复杂查询时,使用SQL语句进行查询。
this is my solution: first transform the return value(RowDataPacket object) into string, and then convert this string into the json object.
这是我的解决方案:首先将返回值(RowDataPacket 对象)转换为字符串,然后将此字符串转换为 json 对象。
The following is code :
以下是代码:
//select all user (查询全部用户)
find: function(req, res, next){
console.log("i am in user find list");
var sql="select * from tb_user";
req.models.tb_user.query(sql,function(err, results) {
console.log('>> results: ', results );
var string=JSON.stringify(results);
console.log('>> string: ', string );
var json = JSON.parse(string);
console.log('>> json: ', json);
console.log('>> user.name: ', json[0].name);
req.list = json;
next();
});
}
The following is console:
以下是控制台:
>> results: [ RowDataPacket {
user_id: '2fc48bd0-a62c-11e5-9a32-a31e4e4cd6a5',
name: 'wuwanyu',
psw: '123',
school: 'Northeastern university',
major: 'Communication engineering',
points: '10',
datems: '1450514441486',
createdAt: Sat Dec 19 2015 16:42:31 GMT+0800 (china标准时间),
updatedAt: Sat Dec 19 2015 16:42:31 GMT+0800 (china标准时间),
ID: 3,
phone: 2147483647 } ]
>> string: [{"user_id":"2fc48bd0-a62c-11e5-9a32-a31e4e4cd6a5","name":"wuwanyu","psw":"123","school":"Northeastern university","major":"Communication engineering","points":"10","datems":"1450514
441486","createdAt":"2015-12-19T08:42:31.000Z","updatedAt":"2015-12-19T08:42:31.000Z","ID":3,"phone":2147483647}]
>> json: [ { user_id: '2fc48bd0-a62c-11e5-9a32-a31e4e4cd6a5',
name: 'wuwanyu',
psw: '123',
school: 'Northeastern university',
major: 'Communication engineering',
points: '10',
datems: '1450514441486',
createdAt: '2015-12-19T08:42:31.000Z',
updatedAt: '2015-12-19T08:42:31.000Z',
ID: 3,
phone: 2147483647 } ]
>> user.name: wuwanyu
回答by Jan ?ourek
You can copy all enumerable own properties of an object to a new one by Object.assign(target, ...sources):
您可以通过Object.assign(target, ...sources)将对象的所有可枚举属性复制到新的属性:
trivial_object = Object.assign({}, non_trivial_object);
so in your scenario, it should be enough to change
所以在你的场景中,改变就足够了
ret.push(i);
to
到
ret.push(Object.assign({}, i));
回答by FranSanchis
With Object.prototype
approach, JSON.parse(JSON.stringify(rows))
returns object, extract values with Object.values()
使用Object.prototype
方法,JSON.parse(JSON.stringify(rows))
返回对象,提取值Object.values()
var resultArray = Object.values(JSON.parse(JSON.stringify(rows)))
Usage:
用法:
resultArray.forEach(function(v){ console.log(v) })
回答by Kumaresan Perumal
you try the code which gives JSON without rowdatapacket:
您尝试使用不带 rowdatapacket 的 JSON 代码:
var ret = [];
conn.query(SQLquery, function(err, rows, fields) {
if (err)
alert("...");
else {
ret = JSON.stringify(rows);
}
doStuffwithTheResult(ret);
}
回答by Julian
going off of jan's answer of shallow-copying the object, another clean implementation using map function,
从 jan 浅复制对象的回答开始,这是另一个使用 map 函数的干净实现,
High level of what this solution does: iterate through all the rows and copy the rows as valid js objects.
此解决方案的高级功能:遍历所有行并将行复制为有效的 js 对象。
// function will be used on every row returned by the query
const objectifyRawPacket = row => ({...row});
// iterate over all items and convert the raw packet row -> js object
const convertedResponse = results.map(objectifyRawPacket);
We leveraged the array map function: it will go over every item in the array, use the item as input to the function, and insert the output of the function into the array you're assigning.
我们利用了数组映射函数:它将遍历数组中的每一项,使用该项作为函数的输入,并将函数的输出插入到您分配的数组中。
more specifically on the objectifyRawPacket function: each time it's called its seeing the "{ RawDataPacket }" from the source array. These objects act a lot like normal objects - the "..." (spread) operator copies items from the array after the periods - essentially copying the items into the object it's being called in.
更具体地说,在 objectifyRawPacket 函数上:每次调用它时都会从源数组中看到“{ RawDataPacket }”。这些对象的行为很像普通对象——“...”(扩展)运算符在句点之后从数组中复制项目——本质上是将项目复制到它被调用的对象中。
The parens around the spread operator on the function are necessary to implicitly return an object from an arrow function.
函数上展开运算符周围的括号是从箭头函数隐式返回对象所必需的。
回答by capaocapao
Simpler way:
更简单的方法:
.then( resp=> {
let resultFromDb= Object.values(resp)[0]
console.log(resultFromDb)
}
In my example I received an object in response. When I use Object.values I have the value of the property as a response, however it comes inside an array, using [0] access the first index of this array, now i have the value to use it where I need it.
在我的示例中,我收到了一个对象作为响应。当我使用 Object.values 时,我将属性的值作为响应,但是它位于一个数组中,使用 [0] 访问该数组的第一个索引,现在我有了在需要的地方使用它的值。
回答by M14
I found an easy way
我找到了一个简单的方法
Object.prototype.parseSqlResult = function () {
return JSON.parse(JSON.stringify(this[0]))
}
At db layer do the parsing as
在 db 层做解析为
let users= await util.knex.raw('select * from user')
return users.parseSqlResult()
This will return elements as normal JSON array.
这将作为普通 JSON 数组返回元素。
回答by Durai Vinoth
Hi try this 100% works:
嗨,试试这个 100% 的作品:
results=JSON.parse(JSON.stringify(results))
doStuffwithTheResult(results);
回答by JaffaMicrobrain
I had this problem when trying to consume a value returned from a stored procedure.
我在尝试使用从存储过程返回的值时遇到了这个问题。
console.log(result[0]);
would output "[ RowDataPacket { datetime: '2019-11-15 16:37:05' } ]".
将输出“[ RowDataPacket { datetime: '2019-11-15 16:37:05' } ]”。
I found that
我找到
console.log(results[0][0].datetime);
Gave me the value I wanted.
给了我想要的价值。