简体   繁体   English

使用Object []方法返回数组

[英]Returning Array with Object[] method

I have a method that is supposed to populate a JComboBox with data gathered from my database, but the only way I've seen to be able to grab the info from the database, is in an Array. 我有一种方法应该使用从数据库中收集的数据填充JComboBox,但是我看到能够从数据库中获取信息的唯一方法是在Array中。 And I need to convert the array to object[] before I can completely compile my program. 在完全编译程序之前,需要将数组转换为object []。 Is there any way to actually do this? 有什么实际方法吗? Or is this going to be a long process? 还是这将是一个漫长的过程? My code is as below. 我的代码如下。

public Object[] getId() {
  Connection con;
  Statement stmt;
  ResultSet rs;

  //Object[] returnId;
  Array returnId;
  try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con = DriverManager.getConnection("jdbc:odbc:collegesys","root","0blivi0n");

    stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
    rs = stmt.executeQuery("SELECT `id` FROM main");

    while(rs.next()) {
      returnId = rs.getArray("id");
    }

    con.close();
  } catch(Exception e) {
    e.printStackTrace();
  }
  return returnId.toObject();
}

Try this: 尝试这个:

 
 
 
  
  return (Object[]) returnId.getArray();
 
  

I gather that you want to collect the value of the "id" column from all rows of table main . 我收集到您想从表main所有行中收集"id"列的值。 Your code will not do that as it's organized. 您的代码无法按照组织的那样进行。 Try this instead: 尝试以下方法:

public Object[] getId() {
  Connection con;
  Statement stmt;
  ResultSet rs;

  //Object[] returnId;
  ArrayList<Object> returnId = new ArrayList<Object>();
  try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con = DriverManager.getConnection("jdbc:odbc:collegesys","root","0blivi0n");

    stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
    rs = stmt.executeQuery("SELECT `id` FROM main");

    while(rs.next()) {
      returnId.add(rs.getObject("id"));
    }

    con.close();
  } catch(Exception e) {
    e.printStackTrace();
  }
  return returnId.toArray(new Object[returnId.size()]);
}

Of course, if you have a better idea of the data type in column id , you can be more specific about the return type and how you get the value (eg, String[] and rs.getString("id") or Integer[] and rs.getInt("id") ). 当然,如果您对id列中的数据类型有更好的了解,则可以更详细地了解返回类型以及如何获取值(例如String[]rs.getString("id")Integer[]rs.getInt("id") )。

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

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