How can i get all the values from all the columns?
Ive tried with this code:
values.add(rs.getString(number));
Where number is the rowcount.
But it only gives me all the values from the last column.
I need to grab the values from every column and then add it to the arraylist.
This is my full code:
// The column count starts from 1
int number = 0;
for ( i = 1; i < columnCount + 1; i++ ) {
number++;
ColumnNames = rsmd.getColumnName(i);
ar.add(ColumnNames);
System.out.println(ar);
}
model.setColumnCount(columnCount);
while ( rs.next() ) {
// values.add(rs.getString(ar.indexOf(i)));
values.add(rs.getString(number));
System.out.println(values);
model.addRow(new Object[] {value1, value2, value3, value4});
}
The ResultSet interface declares getter methods (for example, getBoolean and getLong ) for retrieving column values from the current row. You can retrieve values using either the index number of the column or the alias or name of the column. The column index is usually more efficient. Columns are numbered from 1.
You can get the column count in a table using the getColumnCount() method of the ResultSetMetaData interface. On invoking, this method returns an integer representing the number of columns in the table in the current ResultSet object.
The getRow() method of the ResultSet interface retrieves the current row number/position of the ResultSet pointer. This method returns an integer value representing the current row number to which the ResultSet pointer points to.
You need to use ResultSet#getString to fetch the name . Now, each time you fetch one record, get the name field and add it to your list. Now, since you haven't given enough information about your DTO , so that part you need to find out, how to add this ArrayList to your DTO .
ResultsetMetaData holds your column count too. The snippet below will fill out an Object array for every column in a resultset.
The API doc is your friend: http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSetMetaData.html
ResultSet resultSet = getResultSetFromSomewhere();
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
final int columnCount = resultSetMetaData.getColumnCount();
while (resultSet.next()) {
Object[] values = new Object[columnCount];
for (int i = 1; i <= columnCount; i++) {
values[i - 1] = resultSet.getObject(i);
}
model.addRow(values);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With