简体   繁体   中英

Java return string object

I have a database function that retrieves data and then populates a jtable. I need to change this function so it RETURNS the data from the database within an Object[][] . How can this be done? (I'm unsure on how to store the data on each row iteration - the while loop part in the code below).

public void data() {
    // clear table then load information 
    DefaultTableModel model=(DefaultTableModel)table.getModel();  
         model.getDataVector().removeAllElements();
  table.repaint(); 
  ResultSet rs=null;
  Statement st=null;

    try { 
        Class.forName("java.sql.Driver"); 
        _con = DriverManager.getConnection(_url,_user,_pwd);
        st = _con.createStatement(); 
        String query = "SELECT * FROM table";

        rs = st.executeQuery(query); 

        while (rs.next()) { 
            String d1 = rs.getString("record1"); 
            String d2 = rs.getString("record2");
            model.addRow(new Object[]{d1,d2}); 
        }        
    } catch (Exception e) { 
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (_con != null) {
                _con.close();
            }
        } catch (SQLException ex) {
        }
    }
}

I don't think this method is a good idea for several reasons:

  1. A method should do one thing well. You've got UI, connection acquisition, and querying all mingled in this one method. I'd start breaking them up a bit more. The persistence layer should not know or care that you're using Swing.
  2. Close those resources in individual try/catch blocks in the finally block. You still want the others to close if one throws an exception.
  3. An empty catch block is a terrible idea. Print or log the stack trace.
  4. Create the Connection outside this method and pass it in.
  5. ResultSet and Statement should not be member variables of the class. Make them local to the method.

Just change the method to return what you want instead of void . I wouldn't use an Object [][] ; I'd prefer a List of Maps or some other type that encapsulated a row. Use the column names as the keys in the Map.

here's some code OP has asked for, and yes, OP should pay heed to duffymo's recomendations - I totally agree on them.

  Object[] result = null;

  try{ 

   Class.forName("java.sql.Driver"); 
   _con = DriverManager.getConnection(_url,_user,_pwd);
   st=_con.createStatement(); 

   String query="SELECT COUNT(*) cnt FROM table";
   rs=st.executeQuery(query); 
   Integer size = null;
   if (rs.next()){
       size = rs.getInteger("cnt");
   }

   if (size != null){
     Object[] result = new Object[size];
     query="SELECT * FROM table";    
     rs=st.executeQuery(query); 
     int i = 0;
     while(rs.next())
     { 
         String d1=rs.getString("record1"); 
         String d2=rs.getString("record2");
         result[i++] = new Object[]{d1,d2}; 
     }        
   }
   } 
   catch(Exception e)  
   { 
      //TODO handle exceptions, e.g. rethrow 
      //throw new RuntimeException(e);
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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