2

After executing this query:

con.query("SELECT name FROM members WHERE id=1", function(err, rows, fields) {
   console.log(rows); 
});

this is what I get:

[ RowDataPacket { name: 'John' } ]

I expect only one record and I only want to get John. How do I do that?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Cain Nuke
  • 2,843
  • 5
  • 42
  • 65

2 Answers2

0

Short of writing your own additional function(s) and passing the row object through them your desired result format is not possible based on the design of the mysqljs/mysql package. In a standard SELECT query the result is always an object.

There is a bit of a hack workaround by using the stream function. Below is an example, but you will still end up with more lines of code than you would if you simply accessed the value via rows[0].name in a standard query.

let the_query = con.query('SELECT name FROM members WHERE id = 1;');
the_query
.on('result', function(row) {
  console.log('row.name:', row.name);
  // expected in log:
  // row.name: John
})
.on('end', function() {
  // this chained event can be excluded
  // here for demo purposes
  console.log('all done');
});
dusthaines
  • 1,320
  • 1
  • 11
  • 17
-1
JSON.stringify(RowDataPacket[0].name)

This will output:

John

Dharman
  • 30,962
  • 25
  • 85
  • 135