我是 Java 新手。我正在尝试创建一个类,其中包含一些用于 Java 1.6 中 SQL 操作的实用方法,以用于一般目的。
我已经写下了 a以在数据库上selectMethod
获取 a 的结果。SELECT
问题:如果我的selectMethod
方法返回一个ResultSet
类型,那么当我调用该方法时,其相关资源(ResultSet
, Statement
)将不可避免地保持打开状态:我无法从另一个方法关闭它们,因为它们已被创建到selectMethod
... 另一方面我无法关闭他们在里面selectMethod
,否则后者不会返回任何东西。
所以我的观点是:==> 我怎样才能关闭资源?<==
我不能使用,try-with-resource
因为我使用的是早期版本的 Java。
在类似的问题中,我还没有找到克服这个问题的“一般方法”。
解决方案:目前我只知道两种方法:
A)避免创建一个selectMethod
返回ResultSet
类型的方法,只创建一个在内部执行查询的方法,以及对查询结果的其他操作。然后将所有资源关闭到方法中。
例子:
public String selectMethod(String query, Connection conn) {
Statement stmt = null;
ResultSet rset = null;
String myOutput = "";
try {
stmt = conn.PreparedStatement(query);
rset = st.executeQuery();
myOutput = rs.getString(2); // the "particular task" I perform on the data retrieved
} catch (SQLException e) {
System.out.println(e);
} finally {
rset.close();
stmt.close();
}
return myOutput;
}
...
...
// method call:
String myQuery = "SELECT colA FROM table_name WHERE table_id = 192837465";
String theDataINeeded = selectMethod(myQuery, myConn);
myConn.close();
A) 的缺点:我想要一个通用的 SQL 类,并且不限于特定任务......
B)进入selectMethod
,将数据复制ResultSet
到aCachedRowSet
并返回CachedRowSet
。
例子:
public CachedRowSet selectMethod(String query, Connection conn) {
Statement stmt = null;
ResultSet rset = null;
CachedRowSetImpl crset = null;
try {
stmt = conn.PreparedStatement(query);
rset = st.executeQuery();
crset = new CachedRowSetImpl();
crset.populate(rset);
} catch (SQLException e) {
System.out.println(e);
} finally {
rset.close();
stmt.close();
}
return crset;
}
...
...
// method call:
String myQuery = "SELECT colA FROM table_name WHERE table_id = 192837465";
CachedRowSetImpl theDataINeeded = new CachedRowSetImpl();
theDataINeeded = selectMethod(myQuery, myConn);
myConn.close();
B)的缺点:我害怕在多行选择时内存不足。我无法使用分页进行查询,因为LIMIT... OFFSET...
我的数据库版本低于 Oracle 12g,并且我不想对 insert 进行查询操作row_number() between ... and ...
。我希望我的实用程序可以处理任何类型的查询。
有谁知道其他解决方案?
提前致谢。