I have used a ResultSet
that returns certain number of rows. My code is something like this:
ResultSet res = getData();
if(!res.next())
{
Sy
You could load the ResultSet into a TableModel, then create a JTable that uses that TableModel, and then use the table.getRowCount() method. If you are going to display the result of the query, you have to do it anyway.
ResultSet resultSet;
resultSet = doQuery(something, somethingelse);
KiransTableModel myTableModel = new KiransTableModel(resultSet);
JTable table = new JTable(KiransTableModel);
int rowCount;
rowCount = table.getRowCount;
First, you should create Statement
which can be move cursor by command:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
Then retrieve the ResultSet
as below:
ResultSet rs = stmt.executeQuery(...);
Move cursor to the latest row and get it:
if (rs.last()) {
int rows = rs.getRow();
// Move to beginning
rs.beforeFirst();
...
}
Then rows variable will contains number of rows returned by sql
this my solution
ResultSet rs=Statement.executeQuery("query");
int rowCount=0;
if (!rs.isBeforeFirst())
{
System.out.println("No DATA" );
} else {
while (rs.next()) {
rowCount++;
System.out.println("data1,data2,data3...etc..");
}
System.out.println(rowCount);
rowCount=0;
rs.close();
Statement.close();
}
You can use res.previous()
as follows:
ResulerSet res = getDate();
if(!res.next()) {
System.out.println("No Data Found.");
} else {
res.previous();
while(res.next()) {
//code to display the data in the table.
}
}
A simple getRowCount
method can look like this :
private int getRowCount(ResultSet resultSet) {
if (resultSet == null) {
return 0;
}
try {
resultSet.last();
return resultSet.getRow();
} catch (SQLException exp) {
exp.printStackTrace();
} finally {
try {
resultSet.beforeFirst();
} catch (SQLException exp) {
exp.printStackTrace();
}
}
return 0;
}
Just to be aware that this method will need a scroll sensitive resultSet
, so while creating the connection you have to specify the scroll option. Default is FORWARD and using this method will throw you exception.
rs.last();
int rows = rs.getRow();
rs.beforeFirst();