JAVA使ORACLE 实现DROP TABLE IF EXISTS的功能。ORACLE没有MYSQL等数据库的DROP TABLE IF EXISTS,使用起来非常不便.
删表还要求表必须存在,不存在则删表报错,太麻烦了.如果能实现其他数据库的DROP TABLE IF EXISTS功能就好了.
其实用JAVA代码很好实现.
下面是一段JDBC执行一组SQL语句的代码.其原理很简单:遇到异常(比如”表或视图不存在”)就跳过去,继续执行下一条SQL.
public static void executeSql(List sqls) {
Connection conn = null;
try {
conn = getConn();
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
Statement stmt = null;
try {
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
} catch (SQLException e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
String errorMess = “”;
for(String temp:sqls){
logger.debug(temp);
try {
stmt.executeUpdate(temp);
} catch (SQLException e) {
e.printStackTrace();
errorMess += e.getMessage() + “\n”;
}
// 异常出现,只是记录错误信息,并不终止程序,而是继续执行
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
}
// 如果循环期间执行出错,错误信息就被累加,在结尾这里,就判断一下,有错误信息,就抛异常
if(StringUtils.isNotBlank(errorMess)){
throw new Exception(errorMess);
}
}