-
Jcombox problem......
:confused: i had a problem in Jcombobox... i like items from database.... i used the following code.. it don't have any error..but the items are not displayed in the combobox...can anybody help to solve..this...
Code:
String field[];
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:Stores1");
stmt1=con.createStatement();
stmt2=con.createStatement();
rs=stmt1.executeQuery("select 'SUPPLIER' from Stores");
ResultSetMetaData rsmd = rs.getMetaData();
int rowCount = rsmd.getColumnCount();
if (rs.next()) {
for (int i = 1; i <= rowCount; i++) {
field=new String[i];
field[i] = rs.getString(i);
unit=new JComboBox(field);
}
} else {
rs.close();
rs = null;
}
}
catch (Exception e) {
System.out.println("Error " + e);
}
-
The code
Code:
field=new String[i];
field[i] = rs.getString(i);
will throw an ArrayIndexOutOfBoundsException.
PS. Close those connections in a finally block. If an exception happens (as is happening now), they are never closed.
-
i didn't any exception... instead the values are not updated in combobox...combox box is empty...
wheather the codes are correct ... to updates the data from database to combobox...
-
Did you check the console at all?
Do e.printStackTrace(); in that catch block.
Think about it.
Code:
field=new String[i];
creates an array of size i. The slots in the array are 0, 1, 2, ... i-1; Since i-1 is the last slot, doing
Code:
field[i] = rs.getString(i);
soon after fails since the array does not have index i. Last position is i-1.
-
changed the code....
Inorder to avoid exception... i changed the code.... eventhough i didnt get the database items in the combo box... check wheather it is correct..
Code:
JComboBox unit;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:Stores1");
stmt1=con.createStatement();
stmt2=con.createStatement();
rs=stmt1.executeQuery("select SUPPLIER from Stores");
ResultSetMetaData rsmd = rs.getMetaData();
int rowCount = rsmd.getColumnCount();
if (rs.next()) {
for (int i = 0; i <= rowCount; i++) {
unit.addItem(rs.getString(i));
}
} else {
rs.close();
rs = null;
}
}
catch (Exception e) {
System.out.println("Error " + e);
e.printStackTrace();
}
-
Separate your codes. The code to get values from the database should be in a separate class from your GUI code. The GUI code just needs the data returned in Lists e.t.c.
You then test your DB access method separately. Make sure it returns a list of the values that you expect.
After that you then pass it's results to the combobox and test that next part.
P.S You ignored my suggestion about closing connections in a finally block.
-
Ok ... i ll try ....and come back if any prob comes.....
-
One loophole here.
To avoid resource leakage u have to add a finally block and check like this and close..database use to produce lot of errors because of resource leakage.
if( rs ! = null)
rs.close();
if( stmt1 != null)
stmt1.close();
if( con != null)
con.close();