node-mysql2 icon indicating copy to clipboard operation
node-mysql2 copied to clipboard

execute/query from json like tokenized params

Open ituhin opened this issue 8 years ago • 5 comments

do we have feature like this ? i am unable to get it work using mysql2

pool.query( 'SELECT * FROM tablename WHERE col1 = :pid AND col2 = :tid', {pid:5, tid:6} ) .then((rs)=>{console.log(rs)}) .catch((e)=>{console.log(e)})

this gives error.... i have tried pool.execute() as well but no luck.

of-course i can build the query manually by doing a string replace and escape params etc. but i thought this is a basic feature. and i am aware of features like using the "?", but i need it this way.

could not find this kinda examples in the doc, which uses named placeholders.

ituhin avatar Aug 09 '18 14:08 ituhin

var sql = 'SELECT * FROM relations WHERE parent_id = :pid AND daughter_id = :did' conn / pool .query({sql:sql, namedPlaceholders: true}, {pid:5, did:6})

this doesnt work either

ituhin avatar Aug 09 '18 15:08 ituhin

https://github.com/sidorares/node-mysql2/blob/5f0fb8f1f5035e2c0207490aa2f0b838dc82fdc2/test/integration/connection/test-named-paceholders.js#L28-L94

make sure you enable this via namedPlaceholders: true in parameters

sidorares avatar Aug 09 '18 15:08 sidorares

yea, found it... it works with execute() but not query() along with the config

pool.execute({sql:sql, namedPlaceholders: true}, {pid:5, did:6}) .then((rs)=>{console.log(rs[0])}).catch((e)=>{console.log(e)})

if the 2nd argument is object and not array, then it should be treated like named placeholders automatically. instead of finding that extra config. makes life easier.

in my experience.... most of the time always goes to figuring out small unexpected details

ituhin avatar Aug 09 '18 15:08 ituhin

Need to double check that, but I think "object instead of array param" to flag named placeholders automatically conflicts with connection.query('INSERT INTO posts SET ?', {id: 1, title: 'Hello MySQL'}) use case - this is what mysqljs/mysql allows and what we have for compatibility

sidorares avatar Aug 09 '18 15:08 sidorares

it works with execute() but not query() along with the config

can you show example of sql? should work for both. To debug, try to call named-placeholders in isolation - see example in https://github.com/mysqljs/named-placeholders#usage

sidorares avatar Aug 09 '18 15:08 sidorares