Prevent mysql casting string to int in where clause

不羁岁月 提交于 2019-12-12 18:23:54

问题


I'm trying to prevent mysql from casting a string to an int in a where clause.

The following query returns the correct row for the order

SELECT delivery_name FROM orders WHERE orders_id = '985225'

The following query also returns the same row as it is casting my string to an int, but I'd like to prevent it from returning the row at all (ie, not cast the string given to an int and effectively say, this cannot accurately be cast to an int so don't).

SELECT delivery_name FROM orders WHERE orders_id = '985225a'

I hope that makes sense, any help would be greatly appreciated!


回答1:


You should be able to avoid this scenario altogether, but if you wanted a workaround you could concat a character to the front of the string, something like:

SELECT delivery_name 
FROM orders 
WHERE CONCAT('a',orders_id) = CONCAT('a','985225a')



回答2:


I suggest you to pas that variable as a integer from your application.

SELECT delivery_name FROM orders WHERE orders_id = '985225'

If orders_id is a integer it means for every row in orders engine ill implict cast it to string to evaluate orders_id = '985225' its not just slow but ill render useless any index in orders_id.

if all you can do is edit the SQL i suggest you to cast the variable.

orders_id = CAST('985225' AS INT)

And one final hint, at application layer its more easy do validate input and prevent a non valid integer input from user.




回答3:


Step 1 - remove the single quotes from the sql string. In other words, change this:

WHERE orders_id = '985225'

to this:

WHERE orders_id = 985225

Step 2 - as per @Marc B's comment, ensure you actually have an integer.

Step 3 - Use a query parameter. MySql accepts them as far as I know.



来源:https://stackoverflow.com/questions/20708253/prevent-mysql-casting-string-to-int-in-where-clause

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