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. And I need to convert the array to object[] before I can completely compile my program. 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
. 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")
).
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.