Reputation: 27
so i have this code
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Object[] possibilities=null;
try {
possibilities = getNames();
} catch (Exception ex) {
System.out.println("Thiss error "+ex.getMessage());
}
String s;
// TODO add your handling code here:
s = (String) JOptionPane.showInputDialog(this, "Complete the sentence:\n"
+ "\"Green eggs and...\"",
"Customized Dialog",
JOptionPane.PLAIN_MESSAGE,
null,
possibilities,
"ham"); // TODO add your handling code here:
}
public Object[] getNames() throws Exception {
Object[] possibilities = null;
int i=0;
rs = ds.getResultSet("SELECT name FROM staff");
possibilities= new Object[rs.getMetaData().getColumnCount()];
System.out.println("Result set has data "+rs.next());
while (rs.next()) {
System.out.println("Data from result set "+rs.getString(1));
possibilities[i] = rs.getObject(1);
System.out.println("Data from array "+possibilities[i]);
i++;
}
return possibilities;
}
and i want to get the values of name(String) in the database of the staff so i can use it in the Joptionpane as an option but all i get when i execute this is what i get
Result set has data true
Data from result set jana dfjks
Data from array jana dfjks
Data from result set jkdfhjk jfhkjdsf
Thiss error 1
What can i do to get all results from the database which has more than 20 results.
Solved by replacing possibilities= new Object[rs.getMetaData().getColumnCount()]; with a possibilities= new Object[100];
but i want how i can make it dynamic depending on the number of results returned
Upvotes: 0
Views: 1132
Reputation: 21971
possibilities= new Object[rs.getMetaData().getColumnCount()]; // it is 1
Here, you assigned array size upto column number. But you put the row value into this array. So, it will throw IndexOutofBoundsException
if row number > column number
. To solve it use ArrayList
instead arrays.
List<Object> possibilities=new ArrayList<>();
Upvotes: 0
Reputation: 9579
The number of columns is irrelevant - you know it's only one column because your SELECT statement only selects one column.
You don't know in advance how many rows will be returned. So use of Arrays here is not appropriate. You need some sort of Collection, probably a List.
Some sample code:
List<String> nameList = new ArrayList<String>();
while (rs.next()) {
nameList.add(rs.getString(1));
}
Now your List has all names extracted from the database.
Upvotes: 1