简体   繁体   English

将比较运算符作为参数传递给SQL查询

[英]Passing comparison operator as parameter to SQL query

Is there is anyway to pass comparison operator to MySQL query as parameter? 是否有将比较运算符作为参数传递给MySQL查询?

Let's say I have this query 假设我有这个问题

SELECT * FROM `table1` WHERE `column1` > @p

And instead of > I want to be able to pass < or = depending on condition. 而不是>我希望能够传递<=取决于条件。 I can use string.format() , but I want my query to be parametrized. 我可以使用string.format() ,但我希望我的查询被参数化。

And I don't want to use predefined queries, as long as they differ only in one operator. 我不想使用预定义的查询,只要它们只在一个运算符中有所不同。

Try this: 尝试这个:

SELECT * FROM `table1`
    WHERE (`column1` > @p and @condition = 1)
        or (`column1` = @p and @condition = 0)
        or (`column1` < @p and @condition = -1)

MySQL prepared statements only support binding values for variables. MySQL预处理语句仅支持变量的绑定值。 Replacing arbitrary part of query string (even for table names) is not supported. 不支持替换查询字符串的任意部分(即使是表名)。 In other words, you will have to construct your SQL dynamically on a client. 换句话说,您必须在客户端上动态构造SQL。

Unfortunately that can't be done in order to prevent SQL injection. 不幸的是,为了防止SQL注入,无法做到这一点。

But I can give you an idea(workaround) on how to do it: 但我可以就如何做到这一点给你一个想法(解决方法):

SELECT * FROM `table1` WHERE (`column1` > @p AND @op='>') OR (`column1` = @p AND @op='=') OR ........

So you can pass the operator to @op parameter from your code. 因此,您可以将代码中的运算符传递给@op参数。

It should be better to use a "switch case" for this kind of operations to prevent SQL injection. 为这种操作使用“switch case”来防止SQL注入应该更好。

Try this: 尝试这个:

SET @MyQuery := CONCAT("SELECT * FROM table1 WHERE",@P);
PREPARE stmt1 FROM @MyQuery;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;

And for @P: 对于@P:

SET @P:= "> 1" OR SET @P:="=1" or other condition you need to put it

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM