finally出错!该如何使用?

伟大de虫子 2003-10-06 10:23:18
下面代码运行正常:
———————————————————————————

<%@ 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




无论怎么改都改不好,请大家帮帮忙,感激!
...全文
64 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
liushenling 2003-10-06
  • 打赏
  • 举报
回复
try中的变量是属于自己的私有变量,就算是在catch也中也不能访问!
VVV_lucky 2003-10-06
  • 打赏
  • 举报
回复
就是楼上说的原因。
还有就是你为什么把逻辑结构也写到画面上来了,因该分开,在画面上只现实数据。要不以后维护升级也就累死了。
swinging 2003-10-06
  • 打赏
  • 举报
回复
FINALLY中用到的变量名必须在TRY {}CATCH 块外部声明,
即,在TRY{}CATCH块中声明的变量,不能在FINALLY块中访问到。

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧