繁体   English   中英

我可以在嵌套循环的多个方法中调用sql对象吗

[英]Can I call sql objects within multiple methods in nested loops

我有一个类似下面的条件,我需要填充dto的层以创建结构化xml,这是在每个调用方法中传递preparestatment和结果集对象的正确方法。 还是应该在每种方法中创建一个新的preparestatment和resultset对象。

 PreparedStatement pstmt = null;
    ResultSet resultSet = null;

    public List getList1()
    {
      pstmt = conn.prepareStatement("query1");
      resultSet = pstmt.executeQuery();

      if(resultSet != null & resultSet.getRow() > 0){
      SubsectionsDTO subsections = new SubsectionsDTO();
      SectionDTO sectionDTO = new SectionDTO();
      sectionDTO.setId("");
      sectionDTO.setSubsections(getList2(pstmt ,resultSet));
      } 
    }

    public List getList2()
    {
      pstmt = conn.prepareStatement("query2");
      resultSet = pstmt.executeQuery();

      if(resultSet != null & resultSet.getRow() > 0){
      SubsectionsDTO subsections = new SubsectionsDTO();
      SectionDTO sectionDTO = new SectionDTO();
      sectionDTO.setId("");
      sectionDTO.setSubsections(getList3(pstmt ,resultSet));
      } 
    }

您当前的方法几乎是正确的。 您应该为每个SQL查询创建一个单独的PreparedStatement及其相应的ResultSet

我在您的设计中看到的缺陷:

  • Connection con在类中声明为字段。 最好将Connection保持在尽可能窄的范围内,因此IMO最好将Connection con变量作为本地参数发送给每个方法。 例如:

     public List getList1(Connection con) { //... } 
  • 看起来您将执行相同的查询,但是使用不同的参数来检索相似的数据。 由于您使用的是同一连接,因此最好有一个SQL语句,该语句使用JOIN带来所有数据,然后对数据进行相应的分组。 这是一个例子:

     String sql = "SELECT t1.col1, t1.col1, t2.col3, t2.col4 FROM t1 INNER JOIN t2 ON t1.id = t2.t1id"; PreparedStatement pstmt = con.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); String col1FromT1 = null; EntityT1 t1; while (rs.next()) { if(!rs.getString("col1").equals(col1FromT1)) { //code to build the entity from T1 t1 = new EntityT1(); //fill t1; } col1FromT1 = rs.getString("col1"); EntityT2 t2 = new EntityT2(); //fill t2 t1.addT2(t2); } 
  • 关闭资源。 也许没有发布在您当前的代码中,但是永远不要忘记ResultSetPreparedStatementConnection调用close方法 如果您使用Java 7中的try-with-resources ,则可能会更容易。

暂无
暂无

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

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