日期:2014-05-17  浏览次数:20743 次

在jsp中连接数据库出现了错误,请高手指点~~
简单的代码,连接数据库出现错误!
<%@page contentType ="text/html"%>
<%@page pageEncoding ="GB2312"%>
<%@page import ="java.sql.*"%>
<html>
  <body>
  <%  
  Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver");
  Connection con =
  DriverManager.getConnection("jdbc:odbc:webData");
  Statement smt =con.createStatement();
  String id=new String(request.getParameter("user1"));
  String sql ="select *from xuesheng where xuehao='" +id +"'";
  ResultSet rs=smt.executeQuery(sql);
  rs.next();
  %>
<%=rs.getString(2) %>的信息如下:
专业:<%= rs.getString(3)%><br>
班级:<%=rs.getString(4) %>
</body>
</html>
  </body>
</html>


错误提示:
org.apache.jasper.JasperException: An exception occurred processing JSP page /ceshi.jsp at line 9

6: <%  
7: Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver");
8: Connection con =
9: DriverManager.getConnection("jdbc:odbc:webData");
10: Statement smt =con.createStatement();
11: String id=new String(request.getParameter("user1"));
12: String sql ="select *from xuesheng where xuehao='" +id +"'";


Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:519)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:410)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)


root cause 

javax.servlet.ServletException: java.sql.SQLException: [Microsoft][ODBC 驱动程序管理器] 未发现数据源名称并且未指定默认驱动程序
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:865)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:794)
org.apache.jsp.ceshi_jsp._jspService(ceshi_jsp.java:89)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:386)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)



这是连接数据库的代码 ,哪错了请各位高手解答~~

------解决方案--------------------
如果rs.next()==false那么,rs.getString(2),rs.getString(3)...将会出错。
正确的写法是:
。。。。。。
String sql ="select *from xuesheng where xuehao='" +id +"'";

ResultSet rs=smt.executeQuery(sql);
while(rs.next()){ //或者if(rs.next()){})
%>
<%=rs.getString(2) %>的信息如下:
专业:<%= rs.getString(3)%><br>
班级:<%=rs.getString(4) %>
<%
}//end of while
%>
</body>
</html>
</body>
</html>


------解决方案---------------