|
| 1 | +package testSuite.classes.resultset_forward_correct; |
| 2 | + |
| 3 | + |
| 4 | +// SO 6367737 — "ResultSet: Exception: set type is TYPE_FORWARD_ONLY -- why?" |
| 5 | +// https://stackoverflow.com/questions/6367737 |
| 6 | +// Counting rows by iterating, then calling rs.beforeFirst() to rewind and iterate |
| 7 | +// again. A default ResultSet is TYPE_FORWARD_ONLY, so the backward scroll throws: |
| 8 | +// java.sql.SQLException: Result set type is TYPE_FORWARD_ONLY |
| 9 | +// at ...JdbcOdbcResultSet.beforeFirst(...) |
| 10 | +// Kept as close to the question as possible; the SO lines are wrapped in a method |
| 11 | +// taking a Connection. Pure java.sql; compiles with no JDBC driver present. |
| 12 | +import java.sql.Connection; |
| 13 | +import java.sql.PreparedStatement; |
| 14 | +import java.sql.ResultSet; |
| 15 | +import java.sql.SQLException; |
| 16 | +import java.sql.Statement; |
| 17 | + |
| 18 | +public class ResultSetTests { |
| 19 | + |
| 20 | + int login(Connection con, String username, String password) throws SQLException { |
| 21 | + int typeID = 0; |
| 22 | + |
| 23 | + PreparedStatement pstat = |
| 24 | + con.prepareStatement("select typeid from users where username=? and password=?", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); |
| 25 | + ResultSet rs = pstat.executeQuery(); |
| 26 | + |
| 27 | + rs.beforeFirst(); // State Refinement Error |
| 28 | + |
| 29 | + return typeID; |
| 30 | + } |
| 31 | + |
| 32 | + int login2(Connection con, String username, String password) throws SQLException { |
| 33 | + int typeID = 0; |
| 34 | + PreparedStatement pstat = |
| 35 | + con.prepareStatement("select typeid from users where username=? and password=?", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); |
| 36 | + pstat.setString(1, username); |
| 37 | + pstat.setString(2, password); |
| 38 | + ResultSet rs = pstat.executeQuery(); |
| 39 | + int rowCount = 0; |
| 40 | + while (rs.next()) { |
| 41 | + rowCount++; |
| 42 | + } |
| 43 | + rs.beforeFirst(); // State Refinement Error |
| 44 | + if (rowCount >= 1) { |
| 45 | + while (rs.next()) { |
| 46 | + typeID = rs.getInt(1); |
| 47 | + } |
| 48 | + } |
| 49 | + return typeID; |
| 50 | + } |
| 51 | + |
| 52 | + float readAverage(Connection conn) throws SQLException { |
| 53 | + Statement parentstmt = conn.createStatement(); |
| 54 | + ResultSet parentMessage = |
| 55 | + parentstmt.executeQuery("SELECT SUM(IMPORTANCE) AS IMPAVG FROM MAIL"); |
| 56 | + // FIX (from accepted answer): parentMessage.next(); |
| 57 | + // VIOLATION: cursor is before the first row; getFloat() with no next(). |
| 58 | + if( parentMessage.next()) { |
| 59 | + float avgsum = parentMessage.getFloat("IMPAVG"); |
| 60 | + return avgsum; |
| 61 | + } else { |
| 62 | + return 0.0f; |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments