如何在 sql 查询中传递参数而不在查询本身中明确显示?

How can I pass a parameter in an sql query without making it explicit in the query itself?

我正在测试我的 ignite 缓存,在缓存中插入一个简单的用户,然后通过查询我得到之前输入的用户返回我在编写查询时遇到问题。我注意到这样写:

@Test
    @EnableStreamCacheTestUtil(caches = {@Cache(name = "User", queryEntity = {@QueryEntity(tableName = "USER", keyClass = String.class, valueClass = User.class)})})
    public void Test_expected_Ok() throws Exception {
        Ignite ignite = Ignition.ignite();


        UsersRequest usersRequest = new UsersRequest();
        usersRequest.setName(TestCostants.NAME);
   

        IgniteCache<String, User> igniteCache = ignite.cache("User");
        User user = new User("Ennio","Ragno",90")
        igniteCache.put("1", user);
    

        SqlFieldsQuery sql = new SqlFieldsQuery("SELECT * " +
                " FROM USER WHERE NAME ='ENNIO'");

        int counter = 0;
        List<List<?>> cursor = igniteCache.query(sql).getAll();
        // try(QueryCursor<List<?>> cursor = igniteCache.query(sql)) {
        for (List<?> row : cursor) {
            log.info("SQLQUeryresult:{}", row);
            counter++;
        }
        Assertions.assertEquals(1,counter);
      }

    
    }

测试工作正常,但如果我这样写查询

        //Clearly in the constant that there is the value "ENNIO"
        UsersRequest usersRequest = new UsersRequest();
        usersRequest.setName(TestCostants.NAME);

        //some code

       
        SqlFieldsQuery sql = new SqlFieldsQuery("SELECT * " +
                " FROM USER WHERE NAME = "+usersRequest.getName());

现在它不再起作用了。这是我第一次尝试使用查询和缓存,但从技术上讲,应该不是一样的吗?像这样传递参数时,是否有不同的方式来编写查询?

正确的做法是使用参数替换,避免SQL注入等麻烦:

    //Clearly in the constant that there is the value "ENNIO"
    UsersRequest usersRequest = new UsersRequest();
    usersRequest.setName(TestCostants.NAME);

    //some code

   
    SqlFieldsQuery sql = new SqlFieldsQuery("SELECT * " +
            " FROM USER WHERE NAME = ?").setArgs(usersRequest.getName());

在你的中间代码中,你在缓存中设置了一个值,稍后使用 .getName()

检索该值
        IgniteCache<String, User> igniteCache = ignite.cache("User");
        User user = new User("Ennio","Ragno",90")
        igniteCache.put("1", user);

恩尼奥不同于恩尼奥

SqlFieldsQuery sql = new SqlFieldsQuery("SELECT * " +
                " FROM USER WHERE NAME ='ENNIO'");

当您调用 usersRequest.getName()

时,您的缓存可能 returns 用户名的 ennio

所以两者的区别

 SqlFieldsQuery sql = new SqlFieldsQuery("SELECT * " +
                " FROM USER WHERE NAME ='ENNIO'");

哪个成功,第二个

SqlFieldsQuery sql = new SqlFieldsQuery("SELECT * " +
                " FROM USER WHERE NAME = "+usersRequest.getName());

失败的是第二个是用 Ennio 而不是 ENNIO

调用的