Prepared statement in an array and bind() for X DevAPI

我与影子孤独终老i 提交于 2021-01-29 15:00:53

问题


I want the statement to search a number of Ids. Like so.

const idsStr = "41, 42, 43";
const sqlStr = `SELECT * FROM table where id IN (${idsStr})`;
session.sql(sqlStr).execute()

But if I use bind method, it only captures the first instance of the string, the remaining values are ignored.

const idsStr = "41, 42, 43";
const sqlStr = `SELECT * FROM table where id IN (?)`;
session.sql(sqlStr).bind(idsStr).execute()

I want to make prepared statement according to the API currently support so as to avoid SQL injection.


回答1:


This is a limitation of the API (and the X Plugin itself) and a byproduct of the fact that CRUD expressions support an alternative syntax such as IN [41, 42, 43]. Right now, the only way to do what you want is for the SQL statement itself to contain placeholders for all those ids:

const sqlStr = `SELECT * FROM table where id IN (?, ?, ?)
await session.sql(sqlStr).bind(41, 42, 43).execute()

Of course this does not work if you need a dynamic number of elements in the filtering criteria. In that case, you can resort to something like:

const ids = [41, 42, 43]
const sqlStr = `SELECT * FROM table where id IN (${ids.map(() => '?').join(',')})`
await session.sql(sqlStr).bind(ids).execute()

This is probably a bit convoluted but it's the smartest workaround I can think of at the moment.

In the meantime, maybe you can open a bug report at https://bugs.mysql.com/ using the Connector for Node.js category.

Disclaimer: I'm the lead dev of the MySQL X DevAPI Connector for Node.js



来源:https://stackoverflow.com/questions/60681200/prepared-statement-in-an-array-and-bind-for-x-devapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!