简体   繁体   English

Java返回字符串对象

[英]Java return string object

I have a database function that retrieves data and then populates a jtable. 我有一个数据库函数,该函数检索数据,然后填充一个jtable。 I need to change this function so it RETURNS the data from the database within an Object[][] . 我需要更改此函数,以便它从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). (我不确定如何在每次行迭代中存储数据-以下代码中的while循环部分)。

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. 您已经用这种方法将UI,连接获取和查询混合在一起。 I'd start breaking them up a bit more. 我将开始分解它们。 The persistence layer should not know or care that you're using Swing. 持久层不应该知道或关心您正在使用Swing。
  2. Close those resources in individual try/catch blocks in the finally block. 在finally块的单独try / catch块中关闭这些资源。 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. 在此方法之外创建Connection并将其传入。
  5. ResultSet and Statement should not be member variables of the class. ResultSetStatement不应是该类的成员变量。 Make them local to the method. 使它们在方法本地。

Just change the method to return what you want instead of void . 只需更改方法以返回所需内容即可,而不是void I wouldn't use an Object [][] ; 我不会使用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. 使用列名称作为Map中的键。

here's some code OP has asked for, and yes, OP should pay heed to duffymo's recomendations - I totally agree on them. 这是OP要求的一些代码,是的,OP应该注意duffymo的建议-我完全同意。

  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);
   }

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

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