I have a table in mysql database where some rows are available. I want to retrieve the data from table in my jdbc program where the ResultSet
is forward only. My code is:
import java.sql.*;
public class Test1 {
static{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Connection con=null;
Statement st=null;
ResultSet rs=null;
int id=0;
String name=null;
try {
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/hiitstudents","root", "rustyiron");
st=con.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.TYPE_SCROLL_INSENSITIVE);
String query="select * from students";
rs=st.executeQuery(query);
while(rs.next()){
id=rs.getInt(1);
name=rs.getString(2);
System.out.println(id+"\t"+name);
} ;
while(rs.previous()){
id=rs.getInt(1);
name=rs.getString(2);
System.out.println(id+"\t"+name);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try{
if(rs!=null)
rs.close();
if(st!=null)
st.close();
if(con!=null)
con.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}
but as the default result sets are forward only we cannot call previous()
in it or it should not work, but doing so in my program retrieves the data in reverse order also. What is the problem in my code?