我如何形成对 jdbcTemplate 的查询
How do i form a query for jdbcTemplate
我正在尝试根据参数形成查询,无论 WHERE 子句的参数是否为空。如果我在 if 和 else 上执行此操作,这似乎是一个巨大的代码。还有其他聪明的方法吗??
示例:
String query = "SELECT CUSTOMER_NAME FROM CUSTOMER_TABLE WHERE ";
if(cust_id !=null && !(cust_id.trim().equalsIgnoreCase("")))
{
query = query + "cust_id='"+cust_id+"'";
}
else
{
}
像这样检查所有列,代码看起来一团糟,请告诉我是否有其他方法可以做到这一点
添加到上面的问题:
我也有 like 运算符的参数
示例
if(strCustName!=null)
{
String query = "SELECT * FROM CUSTOMER WHERE CUSTOMER_NAME LIKE '"+strCustName+"';
}
您可以使用NamedParameterJDBCTemplate
您的查询可以是
... WHERE (cust_id=:custIdParam OR :custIdParam is null)
AND (another_column=:another_param OR :another_param is null)
更新:
String sqlstr = "select * from the_table where lastname like :lastname or :lastname is null"
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(datasource);
Map namedParameters = new HashMap();
namedParameters.put("lastname", "%test%");
SqlRowSet result = jt.queryForRowSet( sqlstr ,namedParameters );
来自 the link
我正在尝试根据参数形成查询,无论 WHERE 子句的参数是否为空。如果我在 if 和 else 上执行此操作,这似乎是一个巨大的代码。还有其他聪明的方法吗??
示例:
String query = "SELECT CUSTOMER_NAME FROM CUSTOMER_TABLE WHERE ";
if(cust_id !=null && !(cust_id.trim().equalsIgnoreCase("")))
{
query = query + "cust_id='"+cust_id+"'";
}
else
{
}
像这样检查所有列,代码看起来一团糟,请告诉我是否有其他方法可以做到这一点
添加到上面的问题:
我也有 like 运算符的参数
示例
if(strCustName!=null)
{
String query = "SELECT * FROM CUSTOMER WHERE CUSTOMER_NAME LIKE '"+strCustName+"';
}
您可以使用NamedParameterJDBCTemplate
您的查询可以是
... WHERE (cust_id=:custIdParam OR :custIdParam is null)
AND (another_column=:another_param OR :another_param is null)
更新:
String sqlstr = "select * from the_table where lastname like :lastname or :lastname is null"
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(datasource);
Map namedParameters = new HashMap();
namedParameters.put("lastname", "%test%");
SqlRowSet result = jt.queryForRowSet( sqlstr ,namedParameters );
来自 the link