如何使用 spring 的 jdbcTemplate 在 SQL 查询中指定参数

Posted

技术标签:

【中文标题】如何使用 spring 的 jdbcTemplate 在 SQL 查询中指定参数【英文标题】:How to specify parameters in an SQL query using spring's jdbcTemplate 【发布时间】:2012-06-10 17:29:59 【问题描述】:

如何在下面的 jdbctemplate 示例中指定“age”参数的值?

String sql = "SELECT * FROM CUSTOMER where age = ? ";

    List<Customer> customers = new ArrayList<Customer>();
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

    List<Map> rows = jdbcTemplate.queryForList(sql);
    for (Map row : rows) 
        Customer customer = new Customer();
        customer.setCustId((Long)(row.get("CUST_ID")));
        customer.setName((String)row.get("NAME"));
        customer.setAge((Integer)row.get("AGE"));
        customers.add(customer);
    

return customers;

【问题讨论】:

【参考方案1】:

您可以使用queryForList() 方法将参数作为参数,例如:

List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql, theAge);    

学习阅读 API 文档(以及一般文档)。这就是你学习的方式。

【讨论】:

谢谢,我正在查看文档,但有点困惑,因为它在检索单行或多行时的工作方式与标准 JDBC 略有不同。

以上是关于如何使用 spring 的 jdbcTemplate 在 SQL 查询中指定参数的主要内容,如果未能解决你的问题,请参考以下文章