try
{
}
catch(SQLException se)
{
stmt.close();
conn.close();
stmt=null;
conn=null;
throw new Exception(se.getMessage());
}
{
}
catch(SQLException se)
{
stmt.close();
conn.close();
stmt=null;
conn=null;
throw new Exception(se.getMessage());
}
调试欢乐多
我现在想知道的是,通过throws抛出异常后,如何处理末关闭的连接。
catch{异常}
finally{关闭连接} //(在finally给程序一个统一出口)
finally
{
if (conn != null) {
try{ conn.close(); }
catch(SQLException sqlex2){
System.err("不能关闭数据库连接!");
}
}
}
conn = dataSource.getConnection();
stmt = conn.createStatement();
rs =
stmt.executeQuery("select * from employees where "
+ "username='" + username + "' "
+ "and password='" + password + "'");
if ( rs.next() ) {
user = rs.getString("username");
// Iterate over the results
System.err.println("Username : "
+ rs.getString("username")
+ " Password : " + rs.getString("password"));
}
else {
System.err.println("−−−−>User not found<−−−−");
}
}
catch (SQLException e) {
System.err.println(e.getMessage());
}
finally {
if (rs != null) {
try {
rs.close();
}
catch (SQLException sqle) {
System.err.println(sqle.getMessage());
}
rs = null;
}
if (stmt != null) {
try {
stmt.close();
}
catch (SQLException sqle) {
System.err.println(sqle.getMessage());
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
}
catch (SQLException sqle) {
System.err.println(sqle.getMessage());
}
conn = null;
}
}
return user;
}
例:
public calss a{
public a()
throws SQLException{
try{
b();
}catch(Exception e){
//这里对异常处理。
}
}
}public class b(){
private SDBAccess sdbaccess = new SDBAccess();//数据库工具
public b()
throws SQLException{
connection conn = sdbaccess.getConnection(); //建立Connection
Statement stm = conn.createStatement();
//写一个错误的SQL语句,这样就会将错误抛向上一级。
stm.executeQuery("当前是错误的SQL会出错误");
stmt.close();
conn.close();
}
}
实际上,我在B中抛出的异常,是在A中处理,不用的东西也是在A中处理。但我不知道如何处理,
它仍会继续执行b的 finally
!!!
这就是java中finally关键字的用处.
明白??
public a()
throws SQLException{
try{
b();
}catch(Exception e){
//这里对异常处理。
}finally{
//处理其它情况。
}
}
}是这样吗。。
问题就在这,,我怎么关闭B中产生的Connection 和 Statement ,是否需要关闭。
try{
}catch(
關閉連接;
throw new Exception(e.toString());
}
connection
是传进去的,出来调用完了。
一次COMMIT,这样多个业务方法就可以一起roolback
也可以一起释放。