2017茶叶退税率:JSP问题。在页面中写好连接数据库的代码,连接成功,但,把代码写成类后,编译也不通过。

来源:百度文库 编辑:杭州交通信息网 时间:2024/05/02 16:29:58
JSP问题。在页面中写好连接数据库的代码,连接成功,但,把代码写成类后,编译也不通过。

页面代码:(成功连接)
ResultSet result=null;
Connection con=null;
Statement stmt=null;

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:driver={SQL Server};SERVER=(local);uid=sa;pwd=;database=jspTest");
stmt=con.createStatement();
result=stmt.executeQuery("select * from Member");

改为类体里的代码后:
import java.sql.*;
public class ODBC
{
public ResultSet result=null;
public Connection con=null;
public Statement stmt=null;

public ResultSet conn()
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:driver={SQL Server};SERVER=(local);uid=sa;pwd=;database=jspTest");
stmt=con.createStatement();
result=stmt.executeQuery("select * from Member");
return result;
}
}

编译也不通过
错误提示:
org.apache.jasper.JasperException: Unable to compile class for JSP

An error occurred at line: 11 in the jsp file: /DB.jsp
Generated servlet error:
C:\tomcat 5.0\work\Catalina\localhost\Test\org\apache\jsp\DB_jsp.java:79: unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
^

An error occurred at line: 11 in the jsp file: /DB.jsp
Generated servlet error:
C:\tomcat 5.0\work\Catalina\localhost\Test\org\apache\jsp\DB_jsp.java:80: unreported exception java.sql.SQLException; must be caught or declared to be thrown

An error occurred at line: 11 in the jsp file: /DB.jsp
Generated servlet error:
con = DriverManager.getConnection("jdbc:odbc:driver={SQL Server};SERVER=(local);uid=sa;pwd=;database=jspTest");
^

An error occurred at line: 11 in the jsp file: /DB.jsp
Generated servlet error:
C:\tomcat 5.0\work\Catalina\localhost\Test\org\apache\jsp\DB_jsp.java:81: unreported exception java.sql.SQLException; must be caught or declared to be thrown
stmt=con.createStatement();
^

An error occurred at line: 11 in the jsp file: /DB.jsp
Generated servlet error:
C:\tomcat 5.0\work\Catalina\localhost\Test\org\apache\jsp\DB_jsp.java:82: unreported exception java.sql.SQLException; must be caught or declared to be thrown
result=stmt.executeQuery("select * from Member");
^
4 errors

大侠门,帮帮忙,一定加分

需要捕捉异常,我给你改了一下

import java.sql.*;
public class ODBC
{
public ResultSet result=null;
public Connection con=null;
public Statement stmt=null;

public ResultSet conn()
{
try
{
Class.forName(\"sun.jdbc.odbc.JdbcOdbcDriver\");
con = DriverManager.getConnection(\"jdbc:odbc:driver={SQL Server};SERVER=(local);uid=sa;pwd=;database=jspTest\");
stmt=con.createStatement();
result=stmt.executeQuery(\"select * from Member\");
}catch(Exception e)
{
e.printStackTrace();
}
return result;
}
}

需要捕获异常