ResultSet.getString(1) throws java.sql.SQLException: Invalid operation at current cursor position
Asked Answered
E

5

13

When I run the following servlet:

// package projectcodes;
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
    String UserID = request.getParameter("UserID");
    String UserPassword = request.getParameter("UserPassword");
    String userName = null;
    String Email = null;
    Encrypter encrypter = new Encrypter();
    String hashedPassword = null;
    try {
        hashedPassword = encrypter.hashPassword(UserPassword);
        Context context = new InitialContext();
        DataSource ds = (DataSource)context.lookup("java:comp/env/jdbc/photog");
        Connection connection = ds.getConnection();
        String sqlStatement = "SELECT email,firstname FROM registrationinformation WHERE password='" + hashedPassword + "'";
        PreparedStatement statement = connection.prepareStatement(sqlStatement);
        ResultSet set = statement.executeQuery();
        userName = set.getString(1);  // <<---------- Line number 28
        response.sendRedirect("portfolio_one.jsp");
        // userName = set.getString("FirstName");
        Email = set.getString(3);
        if(set.wasNull() || Email.compareTo(UserID) != 0) {
            // turn to the error page
            response.sendRedirect("LoginFailure.jsp");
        } else {
            // start the session and take to his homepage
            HttpSession session = request.getSession();
            session.setAttribute("UserName", userName);
            session.setMaxInactiveInterval(900); // If the request doesn't come withing 900 seconds the server will invalidate the session
            RequestDispatcher rd = request.getRequestDispatcher("portfolio_one.jsp");
            rd.forward(request, response); // forward to the user home-page
        }
    }catch(Exception exc) {
        System.out.println(exc);
    }

I get the following exceptions:

INFO: java.sql.SQLException: Invalid operation at current cursor position.
at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.client.am.ResultSet.getString(Unknown Source)
at com.sun.gjc.spi.base.ResultSetWrapper.getString(ResultSetWrapper.java:155)

-----> at projectcodes.ValidateDataForSignIn.doPost(ValidateDataForSignIn.java:28

at javax.servlet.http.HttpServlet.service(HttpServlet.java:754)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
    Caused by: org.apache.derby.client.am.SqlException: Invalid operation at current cursor position.
at org.apache.derby.client.am.ResultSet.checkForValidCursorPosition(Unknown Source)
at org.apache.derby.client.am.ResultSet.checkGetterPreconditions(Unknown Source)
... 30 more

The logs above from the server show that line number 28 is the cause of the exception. But i am unable to get the reason for exception. All the columns in the table have a datatype of varchar.

I have highlighted line number 28 (cause of exception according to server logs) in the servlet code.

Erichericha answered 24/4, 2012 at 13:24 Comment(1)
highlighted the exception in the server logErichericha
H
45

You should use the next statement first.

ResultSet set = statement.executeQuery();
if (set.next()) {
    userName = set.getString(1);
    //your logic...
}

UPDATE

As the Java 6 Documentation says

A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

This means when you execute the sentence

ResultSet set = statement.executeQuery();

The ResultSet set will be created and pointing to a row before the first result of the data. You can look it this way:

SELECT email,firstname FROM registrationinformation

    email              | firstname
    ____________________________________
0                                        <= set points to here
1   [email protected]   | Email1 Person
2   [email protected]        | Foo Bar

So, after openning your ResulSet, you execute the method next to move it to the first row.

if(set.next()) 

Now set looks like this.

    email              | firstname
    ____________________________________
0
1   [email protected]   | Email1 Person   <= set points to here
2   [email protected]        | Foo Bar

If you need to read all the data in the ResultSet, you should use a while instead of if:

while(set.next()) {
    //read data from the actual row
    //automatically will try to forward 1 row
}

If the set.next() return false, it means that there was no row to read, so your while loop will end.

More information here.

Housman answered 24/4, 2012 at 13:27 Comment(6)
set.next() moves the cursor 1 row forward. I want to see the data that is there in the set after i have executed the query to extract the data from a particular cell. How do i do that ?Erichericha
Though it works can you please explain what does set.next() do ? I didn't understand from the Doc. Before set.next() where was the cursor positioned ?Erichericha
After the execution of query that asks to get the name and email of the person belonging to the second row,what will be the position of set now ? Will it still be the 0th row ?Erichericha
@SuhailGupta every time you open a ResultSet, this means ResultSet set = statement.executeQuery();, the position will be 0th rowHousman
Then how come this happens : in my query i fetch the FirstName and Email for the password supplied. i.e set.executeQuery("the same query as mentioned") After this when i do if(set.next()) { set.getString("firstName")} I get the name of the person. This name could be the last name in the tableErichericha
@SuhailGupta let us continue this discussion in chatHousman
S
1

You have to set the pointer to the correct position:

while(set.hasNext()){
    set.next();
    String a = set.getString(1);
    String b = set.getString(2);
} 
Spar answered 24/4, 2012 at 13:28 Comment(1)
set.next() moves the cursor 1 row forward. I want to see the data that is there in the set after i have executed the query to extract the data from a particular cell.How do i do that ?Erichericha
G
1

ResultSet set = statement.executeQuery();

Iterate the set and then get String.

        while(set.next()) {
me = set.getString(1);  // <<---------- Line number 28

}
Gadhelic answered 24/4, 2012 at 13:29 Comment(1)
set.next() moves the cursor 1 row forward. I want to see the data that is there in the set after i have executed the query to extract the data from a particular cell. How do i do that ?Erichericha
F
1

after initializing ResultSet check if the cursor has row in it or not e.g.

if(rs.next()){ //your all other works should go here }

Fatalism answered 22/1, 2018 at 11:20 Comment(0)
T
-1

You can get the first with: rs.first()

Taperecord answered 18/12, 2018 at 5:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.