与其传递单个 Date 对象,不如考虑将 Date 对象的 ArrayList 传递给您的foo(...)
方法并使用它。
您有几个选项可以使用。
选项 1:通过更改参数多次执行 PreparedStatement
public void foo(ArrayList<Date> dateList) {
if(dateList == null)
return;
PreparedStatement stmt = null;
ResultSet rs = null;
java.sql.Date sDate = null;
try{
stmt = getConnection().preparedStatement("select * from some_table p where p.start_date <=? and ?<= p.end_date");
for(Date date: dateList){
try{
sDate = new java.sql.Date(date.getTime());
stmt.clearParameters(); //Clear current parameter values
stmt.setDate(1, sDate);
stmt.setDate(2, sDate);
rs = stmt.executeQuery();
//perform your operations
}finally{
sDate = null;
//mange your resultset closing
}
}
}finally{
//your resource management code
}
}
选项 2:创建一个 SQL 查询,考虑到您在列表中的日期数,执行此语句,然后使用结果集。
public void foo(ArrayList<Date> dateList) {
if(dateList == null)
return;
PreparedStatement stmt = null;
ResultSet rs = null;
java.sql.Date sDate = null;
StringBuilder builder = new StringBuilder();
try{
//1. Create your dynamic statement
builder.append("SELECT * FROM some_table p WHERE \n");
for(int index = 0; index < dateList.length; index++){
if(index > 0)
builder.append(" OR \n");
builder.append("(p.start_date <=? and ?<= p.end_date)");
}
stmt = getConnection().preparedStatement(builder.toString());
//2. Set the parameters
int index = 1;
for(Date date: dateList){
try{
sDate = new java.sql.Date(date.getTime());
stmt.setDate(index, sDate);
stmt.setDate(index+1, sDate);
index += 2;
}finally{
sDate = null;
//mange your resultset closing
}
}
//3. execute your query
rs = stmt.executeQuery();
//4. perform your operations
}finally{
builder = null;
//your resource management code
}
}