Java – ResultSet.getString(1) throws java.sql.SQLException: Invalid operation at current cursor position


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
        // userName = set.getString("FirstName");
        Email = set.getString(3);
        if(set.wasNull() || Email.compareTo(UserID) != 0) {
            // turn to the error page
        } 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) {

I get the following exceptions:

INFO: java.sql.SQLException: Invalid operation at current cursor position.
at Source)
at Source)
at Source)
at com.sun.gjc.spi.base.ResultSetWrapper.getString(

-----> at projectcodes.ValidateDataForSignIn.doPost(

at javax.servlet.http.HttpServlet.service(
at javax.servlet.http.HttpServlet.service(
at org.apache.catalina.core.StandardWrapper.service(
at org.apache.catalina.core.StandardWrapperValve.invoke(
at org.apache.catalina.core.StandardContextValve.invoke(
at org.apache.catalina.core.StandardPipeline.doInvoke(
at org.apache.catalina.core.StandardPipeline.invoke(
at com.sun.enterprise.web.WebPipeline.invoke(
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(
at org.apache.catalina.core.StandardHostValve.invoke(
at org.apache.catalina.connector.CoyoteAdapter.doService(
at org.apache.catalina.connector.CoyoteAdapter.service(
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(
at com.sun.grizzly.http.ProcessorTask.doProcess(
at com.sun.grizzly.http.ProcessorTask.process(
at com.sun.grizzly.http.DefaultProtocolFilter.execute(
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(
at com.sun.grizzly.DefaultProtocolChain.execute(
at com.sun.grizzly.DefaultProtocolChain.execute(
at com.sun.grizzly.http.HttpProtocolChain.execute(
at com.sun.grizzly.ProtocolChainContextTask.doCall(
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(
at com.sun.grizzly.util.AbstractThreadPool$
    Caused by: Invalid operation at current cursor position.
at Source)
at 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.

Best Solution

You should use the next statement first.

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


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   | Email1 Person
2        | Foo Bar

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


Now set looks like this.

    email              | firstname
1   | Email1 Person   <= set points to here
2        | Foo Bar

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

while( {
    //read data from the actual row
    //automatically will try to forward 1 row

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

More information here.

Related Question