如何将ResultSet的内容作为映射返回?

时间:2016-09-06 08:56:16

标签: java sql oracle java-8

我想知道如何将查询的结果集作为地图返回。 这是我的查询,其中'nameCodesString'是一个字符串列表,例如('raul', 'peter', 'shawn')

try (PreparedStatement stmt = conn.prepareStatement("select n.CODE, l.VALUE"
                                + " from TNAME n join TPROPERTIES l on n.UIDPK = l.OBJECT_UID"
                                + " where n.CODE IN (" + nameCodesString + ")")) {
    try (ResultSet rs = stmt.executeQuery()) {
        while (rs.next()) {
            log.info("rs {}",rs);
            nameCode = rs.getString(1);
            displayName = rs.getString(2);
            Person.add(new PersonDTO(nameCode, displayName, ""));
        }
    }
}

结果应该是代码和值。我不确定如何在与数据库的一个连接中完成所有这些操作。

2 个答案:

答案 0 :(得分:0)

你好,这是我的建议

 String req="select n.CODE, l.VALUE from TNAME n join"
 +" TPROPERTIES l on n.UIDPK      = l.OBJECT_UID "
 +" where n.CODE IN ?";
 PreparedStatement stmt=null;
 ResultSet rs=null;

 try{
     stmt=conn.prepareStatement(req);
     stmt.setString(1, nameCodesString);
     rs=stmt.executeQuery();
     while(rs.next()){
       nameCode = rs.getString(1);
       displayName = rs.getString(2);
       Person.add(new PersonDTO(nameCode, displayName, ""));
     }
  }
  catch(SQLException ex){
     System.out.println(ex);
  }
  finally{
     if(rs!=null){
           try{
               rs.close();
           }
           catch(SQLException ex){}
       }
      if(stmt!=null){
           try{
               stmt.close();
           }
           catch(SQLException ex){}
      }
     if(conn!=null){
         try{
              conn.close();
         }
         catch(SQLException ex){}
     }
  }

这只是我的建议,我希望它可以成为你的小费! 最好的问候......

答案 1 :(得分:0)

我无法理解应该如何使用preparedStatements。最后我决定不使用它们并坚持执行查询字符串:

Map<String, String> personDetails = new Hashmap();
try (Connection conn = dataSource.getConnection();
   Statement stmt = conn.createStatement();
   ResultSet rs = stmt.executeQuery("select n.CODE, l.VALUE"
              + " from TNAME n join TPROPERTIES l on n.UIDPK = l.OBJECT_UID"
              + " where n.CODE IN (" + nameCodesString + ")")) {
       while (rs.next()) {
          nameCode = rs.getString(1);
          displayName = rs.getString(2);
          personDetails.put(nameCode, displayName); 
       }
}