java - ResultSet.getString(1) 抛出 java.sql.SQLException : Invalid operation at current cursor position

标签 java jdbc resultset sqlexception

当我运行以下 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);
    }

我遇到以下异常:

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

上面来自服务器的日志显示第 28 行是异常的原因。但我无法得到异常的原因。表中的所有列的数据类型均为 varchar。

我在 servlet 代码中突出显示了第 28 行(根据服务器日志导致异常的原因)

最佳答案

您应该首先使用next 语句。

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

更新

正如 Java 6 文档所述

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.

这意味着当你执行句子时

ResultSet set = statement.executeQuery();

将创建 ResultSet set 并指向数据的第一个结果之前的一行。你可以这样看:

从注册信息中选择电子邮件、名字

    email              | firstname
    ____________________________________
0                                        <= set points to here
1   email1@gmail.com   | Email1 Person
2   foo@bar.com        | Foo Bar

因此,打开 ResulSet 后,执行方法 next 将其移动到第一行。

if(set.next()) 

现在set看起来像这样。

    email              | firstname
    ____________________________________
0
1   email1@gmail.com   | Email1 Person   <= set points to here
2   foo@bar.com        | Foo Bar

如果需要读取ResultSet中的所有数据,应该使用while而不是if:

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

如果set.next()返回 false,则意味着没有要读取的行,因此 while 循环将结束。

更多信息here .

关于java - ResultSet.getString(1) 抛出 java.sql.SQLException : Invalid operation at current cursor position,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30111187/

相关文章:

java - Java EE 中已弃用的实体 Bean 与 @Entity 注释之间的关系?

java - AngularJS中的Spring Security返回403禁止登录

java - 检查 JDBC 请求是否正确执行

java - 我可以在 Java 中使用 resultset.getBoolean 在 SQL 中获取 Tinyint

java - 如何多次使用一个按钮?

java - Tomcat 中的跨操作系统开发。 Linux 下antiJARLocking 和antiResourceLocking 可以设置为True 吗?

java - 如何更新JTable中的数据? (有代码)

java - 如果sql查询什么也找不到怎么处理?在java中使用结果集

java - 在 JSP 中使用 MySQL 连接到 Tomcat 服务器

java - ResultSet 的 Oracle JDBC 性能