JDBC:从数据库中取数据的一个bug
先看错误信息:
1 java.sql.SQLException: Before start of result set 2 at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:910) 3 at com.mysql.jdbc.ResultSet.checkRowPos(ResultSet.java:720) 4 at com.mysql.jdbc.ResultSet.getStringInternal(ResultSet.java:5624) 5 at com.mysql.jdbc.ResultSet.getString(ResultSet.java:5544) 6 at hw5servlet.doGet(hw5servlet.java:38) 7 at hw5servlet.doPost(hw5servlet.java:62) 8 at javax.servlet.http.HttpServlet.service(HttpServlet.java:643) 9 at javax.servlet.http.HttpServlet.service(HttpServlet.java:723) 10 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) 11 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) 12 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) 13 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) 14 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) 15 at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) 16 at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) 17 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) 18 at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:879) 19 at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:617) 20 at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1760) 21 at java.lang.Thread.run(Thread.java:745)
再看编写的JDBC查看代码(如下):
1 Class.forName("com.mysql.jdbc.Driver"); 2 Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/day36","root","root"); 3 String insertString="select password from register where email="+email+";"; 4 //String insertString="insert into register values(?,?,?)"; 5 //System.out.println("hw5servlet.doGet()"+insertString); 6 Statement ps = connection.createStatement(); 7 boolean execute = ps.execute(insertString); 8 //ps.executeQuery(insertString); 9 if(execute){ 10 ResultSet rs = ps.getResultSet(); 11 //rs.beforeFirst(); 12 //rs.next();
//本以为从数据库中去代码只有一行,默认应该是在第一行的,然后直接rs.getString(1)就可以。
//但事实不然,getString()时一定要有rs.next().
13 String password1 = rs.getString(1); 14 System.out.println("hw5servlet.doGet()"+password1); 15 if(password.equals(password1)){ 16 response.getWriter().write("登陆成功"); 17 }else { 18 response.getWriter().write("密码错误,请重新登录"); 19 response.sendRedirect("/Day36_JDBC_hw4/index.jsp"); 20 } 21 }
找了许久没找到,然后百度:http://blog.csdn.net/killua_hzl/article/details/6073618
原创作品,转载请注明出处!