Why ResultSet's index in Java Starts with '1' instead of zero?

Viewed 10910

I am trying to access index 0 in ResultSet but I am getting exception

 java.sql.SQLException: Column Index out of range, 0 < 1.

Code :

c = db.getConnection();

String prefQuery = "SELECT pLab from practicals where className = ? AND pFacName = ?";
PreparedStatement stPref = c.prepareStatement(prefQuery);
stPref.setString(1, className);
stPref.setString(2, facName);
ResultSet rsPref = stPref.executeQuery();

while (rsPref.next()){
    MainClass.show(rsPref.getString(0));
}
1 Answers

ResultSet columns getters methods start index with 1 (although index usually start with 0 in Java)

The ResultSet interface provides getter methods (getBoolean, getLong, and so on) for retrieving column values from the current row. Values can be retrieved using either the index number of the column or the name of the column. In general, using the column index will be more efficient. Columns are numbered from 1

You should change to

MainClass.show(rsPref.getString(1));

Similar to your index in setter stPref.setString(1, className);

Related