[英]JDBC RowSets using singleton Connection
我正在使用javax.sql.rowset.JdbcRowSet
和com.sun.rowset.JdbcRowSetImpl
来处理数据。 一切正常,但是我收到警告,我可能会发生资源泄漏。
另外,我在始终打开的JdbcRowSet构造函数中使用单例连接,但是当我使用JdbcRowSet close()
时,不能在下一个方法中使用它。
这是代码。
public static Connection conn = DBConnection.getInstance()
.getConnection();
(not the exact work, only a sample code)
private static void function1() {
try {
JdbcRowSet myrs = new JdbcRowSetImpl(conn);
myrs.setCommand("SELECT * FROM `table1`");
myrs.execute();
//result iteration
myrs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void function2() {
same as function1 (for example, not really important here)
}
public static void start(){
function1();
function2();
}
当它在function2()
执行myrs
,出现错误:
at com.sun.rowset.JdbcRowSetImpl.execute(Unknown Source)
有人知道如何解决吗?
这是关闭的JdbcRowSetImpl实现
public void close() throws SQLException {
if (rs != null)
rs.close();
if (ps != null)
ps.close();
if (conn != null)
conn.close();
}
由于JdbcRowSetImpl.close()将关闭连接,因此适合当前体系结构的最佳方法可能是创建一个JdbcRowSet成员或实例单例,在您希望对连接进行分类时将其关闭。 您的function1和function2看起来像这样
public static Connection conn = DBConnection.getInstance()
.getConnection();
//Implementation of DBRowSet left as an exercise for the ambitious.
public static JdbcRowSet myrs = DBRowSet.getInstance();
private static void function1() {
try {
myrs.setCommand("SELECT * FROM `table1`");
myrs.execute();
//result iteration
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void function2() {
try {
myrs.setCommand("SELECT * FROM `table2`");
myrs.execute();
//result iteration
} catch (SQLException e) {
e.printStackTrace();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.