当前位置: 代码迷 >> J2EE >> 求解释,详细点的,帮忙剖析一下解决思路
  详细解决方案

求解释,详细点的,帮忙剖析一下解决思路

热度:56   发布时间:2016-04-22 01:44:52.0
求解释,详细点的,帮忙剖析一下
public static int exeUpdate(String sqlName) {
int result = 0;
// 成功返回1
Connection conn = null;
Statement stmt = null;

try {
DataSource ds = getDataSource(null);
conn = ds.getConnection();

if (conn == null) {
System.out.println("不能得到连接");
}
String command = sqlName.trim();
conn.setAutoCommit(false);
stmt = conn.createStatement();
result = stmt.executeUpdate(command);
commit(conn);
stmt.close();
stmt = null;
return result;
} catch (Exception e) {

result = -1;
if (conn != null) {
rollback(conn);

try {
conn.close();
conn = null;
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

}
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}

} finally {

try {
if (conn != null) {
conn.close();
conn = null;
}
} catch (Exception e) {
e.printStackTrace();
}

}
return result;
}

------解决方案--------------------
public static int exeUpdate(String sqlName) {
int result = 0;
// 成功返回1
Connection conn = null;
Statement stmt = null;

try {
//创建数据库连接
DataSource ds = getDataSource(null);
conn = ds.getConnection();

//判断连接是否为空
if (conn == null) {
System.out.println("不能得到连接");
}
//去除参数前后空格
String command = sqlName.trim();
conn.setAutoCommit(false);
//创建容器
stmt = conn.createStatement();
//修改数据
result = stmt.executeUpdate(command);
commit(conn);
//关闭容器
stmt.close();
stmt = null;
return result;
} catch (Exception e) {
//抛出异常处理
result = -1;
if (conn != null) {
rollback(conn);//数据库回滚

try {
//关闭连接
conn.close();
conn = null;
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

}
//如果容器不为null,关闭容器
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}

} finally {

try {
if (conn != null) {
conn.close();
conn = null;
}
} catch (Exception e) {
e.printStackTrace();
}

}
return result;

  相关解决方案