finally出错!该如何使用?
下面代码运行正常:
———————————————————————————
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<html>
<body>
<font color=blue>SQLserver连接测试:</font><br>
<%
try
{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
String connstr="jdbc:microsoft:sqlserver://arbiter:1433;DatabaseName=test";
Connection conn= DriverManager.getConnection(connstr,"aa","123456");
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from aa_user";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
out.print("<br>" + rs.getString(1));
out.print("," + rs.getString(2));
out.print("," + rs.getString(3));
}
out.print("<br><br>数据库操作成功,恭喜你");
}
catch(Exception ex)
{
out.print("error:"+ex.toString());
}
rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
为了能在抛出异常时也能关闭数据库的连接,节省资源,把上面的
rs.close();
stmt.close();
conn.close();
改成如下代码:
finally
{
if(rs!=null){
try{rs.close();}
catch(Exception rs_err){out.print("error:"+rs_err.toString());}
}
if(stmt!=null){
try{stmt.close();}
catch(Exception stmt_err){out.print("error:"+stmt_err.toString());}
}
if(conn!=null){
try{conn.close();}
catch(Exception conn_err){out.print("error:"+conn_err.toString());}
}
}
改了之后,出现下面的错误:
500 Servlet Exception
/sqltest.jsp:55: cannot resolve symbol
symbol : variable rs
location: class _sqltest__jsp
if(rs!=null){
^
/sqltest.jsp:57: cannot resolve symbol
symbol : variable rs
location: class _sqltest__jsp
try{rs.close();}
^
/sqltest.jsp:63: cannot resolve symbol
symbol : variable conn
location: class _sqltest__jsp
if(conn!=null){
^
/sqltest.jsp:65: cannot resolve symbol
symbol : variable conn
location: class _sqltest__jsp
try{conn.close();}
^
4 errors
无论怎么改都改不好,请大家帮帮忙,感激!