简体   繁体   English

关闭ResultSets和PreparedStatements的快速修复

[英]Quick fixes for closing ResultSets and PreparedStatements

I got some module interfacing problem, due to a library usage. 由于使用了库,我遇到了一些模块接口问题。

http://technojeeves.com/joomla/index.php/free/59-resultset-to-tablemodel http://technojeeves.com/joomla/index.php/free/59-resultset-to-tablemodel

I had to pass the Resultset Object out of the Database Module. 我必须将结果集对象传递出数据库模块。 As you might think, It is not that modular for programming. 您可能会想到,它不是用于编程的模块化。 So I did something like this 所以我做了这样的事情

public ResultSet getEmployee()
{
   PreparedStatement pst = null;
   ResultSet rs = null;
   String sql = "select * from employees";
   try
   {
      pst = conn.PreparedStatement(sql);
      rs = pst.executeQuery();
   }
   catch (SQLException e)
   {
    OptionPane.showMessageDialog(null, "Database Access Error");
   }
   return rs;
}

On some display module, I did 在某些显示模块上,我做了

tblEmp.setModel(DbUtils.resultSetToTableModel(rs));

Now I am hassling to finish polishing up my project for delivery and suddenly found this post. 现在,我正忙于完善要交付的项目,突然发现了这个帖子。

Where to close java PreparedStatements and ResultSets? 在哪里关闭Java PreparedStatements和ResultSets?

And come to realize what I all did was wrong. 并意识到我所做的一切都是错误的。 I had to pass out a "set" object out of the Database module. 我必须从数据库模块中传递出一个“设置”对象。 But as you see, the library is not intended to be used that way. 但是如您所见,该库并非旨在以这种方式使用。 How can I fix that in order to close all resultsets properly? 如何解决此问题以便正确关闭所有结果集? Thanks 谢谢

I suggest you look into using a CachedRowSet instead of the ResultSet . 我建议您考虑使用CachedRowSet而不是ResultSet In fact you don't even need to change the method signature, just change the method to return RowSetProvider.newFactory().createCachedRowSet(rs); 实际上,您甚至不需要更改方法签名,只需更改方法以返回RowSetProvider.newFactory().createCachedRowSet(rs); and close rs and pst in your finally block. 并在您的finally块中关闭rspst

I can't agree with @ElliottFrisch's suggestion. 我不同意@ElliottFrisch的建议。 That just mixes up the GUI with the database code. 那只是将GUI与数据库代码混合在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM