如何动态地为PreparedStatement分配值?

时间:2015-01-30 17:10:58

标签: java sql prepared-statement

当前情景:

String query= "select emp_role from emp where emp_id = ?";
String query= "select address.phone_no from address, emp where address.address_id=emp.address_id and emp.emp_id = ?";

PreparedStatement prepatedStatement = connection.prepareStatement(query);
prepatedStatement.setInt(1, empId);
ResultSet rs = prepatedStatement.executeQuery();

预期情景:

当我有多个输入的查询时,如下所述

String query= "select emp_role from emp where emp_id = ? and emp_plan = ?";
String query= "select emp_id,emp_name from (select emp_id,emp_name from emp_1 where emp_1_id = ?)union(select emp_id,emp_name from emp_2 where emp_2_id = ?)";

我需要有一个通用的prepatedStatement逻辑来执行此操作。

看看 - How to create a prepared statement dynamically - and re-use the query

这个逻辑工作正常,但我仍然需要设置值来显式映射。

1 个答案:

答案 0 :(得分:0)

没有自动的方式来做这些事情,但你可以通过以下方式改进它:

List<String> empParameters = getMeParameters();//may be factory here?
ResultSet rs = getResultSet(.....);
......
private ResultSet getResultSet(PreparedStatement prepatedStatement,   List<String> empParameters) {
     int i = 0;
     for (String empParameter : empParameters) {
         prepatedStatement.setInt(i++, empParameter);
     }
     return prepatedStatement.executeQuery();
}