gpt4 book ai didi

java - 使用准备好的语句查询列表 (JDBC)

转载 作者:搜寻专家 更新时间:2023-10-30 19:49:02 27 4
gpt4 key购买 nike

我目前有一个方法如下所示:

public void foo(Date date) {
PreparedStatement stmt;
ResultSet rs;
java.sql.Date sDate = new java.sql.Date(date.getTime());

try {
String sql = "select * from some_table p where p.start_date <=? and ?<= p.end_date";
stmt = getConnection().preparedStatement(sql);
stmt.setDate(1, sDate);
stmt.setDate(2, sDate);
rs = stmt.executeQuery();
//...
} finally {
if (rs != null) { rs.close(); }
if (stmt != null) { stmt.close(); }
}
}

现在我不想传递一个 Date 对象,而是想传递日期列表 ( List<Date> dates )。我想我在技术上可以多次调用 foo,同时遍历列表,但有没有一种方法可以实现这一点而不必多次调用 foo?

最佳答案

与其传递单个 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
}

}

关于java - 使用准备好的语句查询列表 (JDBC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13113105/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com