node-mysql2
node-mysql2 copied to clipboard
What is the correct syntax for including SQL values AND rowsAsArray option in a query?
Discussed in https://github.com/sidorares/node-mysql2/discussions/3095
This is really a documentation enhancement request and should not be moved to a discussion.
There is no place in the docs where the correct syntax for using both rowsAsArray and a SQL value is shown.
Originally posted by millerbryan October 2, 2024
I've looked at all the examples in the docs which use rowsAsArray and it isn't clear how to specify it in a query (rather than in the connection) when passing in SQL values. Is this possible to pass both?
// simplified code
const sql = "select county_name from static_web_data.state_counties where state_name = ?";
const state = "TX"
try {
const [rows, fields] = await pool.query({sql, [state], rowsAsArray: true});
if (rows) {
return rows;
}
} catch (err) {
console.log(err);
}
```</div>
Thanks, @millerbryan 🤝
Based on the types, there are two ways to use it:
https://github.com/sidorares/node-mysql2/blob/c06d2aea35cf2e45386bae5804d712f8902652ad/typings/mysql/lib/protocol/sequences/promise/QueryableBase.d.ts#L13-L19 https://github.com/sidorares/node-mysql2/blob/c06d2aea35cf2e45386bae5804d712f8902652ad/typings/mysql/lib/protocol/sequences/Query.d.ts#L7-L15
// A
pool.query({ sql: '', values: [], rowsAsArray: true });
// B
pool.query({ sql: '', rowsAsArray: true }, []);
I'll check it out in practice and also what happens if both are used at the same time with different values:
🧐💭
pool.query({ sql: '', values: [], rowsAsArray: true }, []);
Thank you @wellwelwel and apologies for missing your response.
I will have a go at your syntax now and see what happens.
The syntax works perfectly but the result set is different from what I expected. It includes quotes and [ ] for each item.
JavaScript syntax used: const [rows_array, fields] = await pool.query({ sql: sql, values: [state], rowsAsArray: true });
I was hoping for something more like this: