简体   繁体   English

关闭连接后使用结果集数据

[英]Using resultset data after closing the connection

I'm trying to write a small code snippet where I need to get some data from a database and then process the result in some other java file. 我正在尝试编写一个小的代码段,我需要从数据库中获取一些数据,然后在其他Java文件中处理结果。 I tried writing a program and the execution for the same was failing with error "Cannot access resultset as the connection was already closed". 我尝试编写一个程序,该程序的执行失败,并显示错误“由于连接已关闭,无法访问结果集”。

Is there any way can we store the result fetched from database some where (Ex.some arraylist) and use it for computation after closing the connection? 有什么办法可以将从数据库中获取的结果存储在某个地方(例如somearraylist),并在关闭连接后将其用于计算? If yes, can someone please explain it with example? 如果是,有人可以举例说明吗? Slightly handicapped since I'm new to it. 由于我是新手,因此略有残障。

Class A { 

  public Map<String, Object> loadDat(int acc,Map<String,Object> result) 
      throws Exception { 
    Class.forName("com.teradata.jdbc.TeraDriver"); 
    Connection conn = DriverManager.getConnection(connectionString, user, password); 
    query = "select * from mytable where id="+acc; 
    PreparedStatement stmt = conn.prepareStatement(query); 
    ResultSet rs=stmt.executeQuery(); 
    result.put(" Result", rs) ; 
    return result; 
  }

}

In general, don't code JDBC database access by hand. 通常,请勿手动编写JDBC数据库访问代码。 Libraries already exist that do all the low level JDBC handling now and they do it correctly. 现在已经存在可以执行所有低层JDBC处理的库,并且它们可以正确执行。 You will never do it better than an one of the mature, open source projects already do it. 您将永远做不到比已经成熟的成熟开源项目之一更好的了。

Instead, learn and use something like MyBatis . 相反,学习和使用MyBatis之类的东西。 If you use Spring, here is a link to the Mybatis-Spring project . 如果您使用Spring,这是Mybatis-Spring项目的链接。

MyBatis conceals all of the data conversion and JDBC junk. MyBatis隐藏了所有数据转换和JDBC垃圾。 Instead, you define your query in a simple XML file and receive a List as the result of a query. 相反,您可以在一个简单的XML文件中定义查询,并接收作为查询结果的列表。

Just to add to @DwB's answer that is correct. 只是添加到@DwB的答案是正确的。

You can 1) retrieve all rows from your query into a Java List, 2) then close the connection, and 3) then use the Java List in another class (for further processing). 您可以1)将查询中的所有行检索到Java列表中; 2)然后关闭连接; 3)然后在另一个类中使用Java列表(以进行进一步处理)。

If you close the connection after retrieving only part of the result set, you'll lose the rest of it and will receive the error you mention. 如果仅检索结果集的一部分后关闭连接,则将丢失其余部分,并会收到您提到的错误。 Don't do it this way. 不要这样

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

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