Read the Following Code:
public class selectTable { public static ResultSet rSet; public static int total=0; public static ResultSet onLoad_Opetations(Connection Conn, int rownum,String sql) { int rowNum=rownum; int totalrec=0; try { Conn=ConnectionODBC.getConnection(); Statement stmt = Conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); String sqlStmt = sql; rSet = stmt.executeQuery(sqlStmt); total = rSet.getRow(); } catch(Exception e) { System.out.println(e.getMessage()); } System.out.println("Total Number of Records="+totalrec); return rSet; } }
The folowing code dos't show actual total:
total = rSet.getRow();
my jTable display 4 record in jTable but total = 0; when I evaluate through debug, it shows:
total=(int)0;
rather than total=(int)4 And if I use
rSet=last(); above from the code total = rSet.getRow();
then total shows accurate value = 4 but rSet return nothing. then jTable is empty. Update me!
Getting the number of rows using methodsThe last() method of the ResultSet interface moves the cursor to the last row of the ResultSet and, the getRow() method returns the index/position of the current row.
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 SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows.
The SQL Count() function returns the number of rows in a table. Using this you can get the number of rows in a table.
BalusC's answer is right! but I have to mention according to the user instance variable such as:
rSet.last(); total = rSet.getRow();
and then which you are missing
rSet.beforeFirst();
the remaining code is same you will get your desire result.
You need to call ResultSet#beforeFirst()
to put the cursor back to before the first row before you return the ResultSet
object. This way the user will be able to use next()
the usual way.
resultSet.last(); rows = resultSet.getRow(); resultSet.beforeFirst(); return resultSet;
However, you have bigger problems with the code given as far. It's leaking DB resources and it is also not a proper OOP approach. Lookup the DAO pattern. Ultimately you'd like to end up as
public List<Operations> list() throws SQLException { // Declare Connection, Statement, ResultSet, List<Operation>. try { // Use Connection, Statement, ResultSet. while (resultSet.next()) { // Add new Operation to list. } } finally { // Close ResultSet, Statement, Connection. } return list; }
This way the caller has just to use List#size()
to know about the number of records.
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