Java代码判断数据库中某张表是否存在

最近在开发一个同步数据的统计任务的时候遇到一个问题:要在Java代码中判断数据库中某张表是否存在,查资料后,总结了以下两种方法:

1、使用JdbcTemplate bean 1、使用JdbcTemplate bean
public boolean validateTableNameExist(String tableName) {
           int tableNum = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM ALL_TABLES WHERE TABLE_NAME=" + tableName);
           if (tableNum > 0) {
                 return true;
           }else {
                 return false;
           }
     }
public boolean validateTableNameExist(String tableName) { int tableNum = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM ALL_TABLES WHERE TABLE_NAME=" + tableName); if (tableNum > 0) { return true; }else { return false; } }
2、使用Connection对象 2、使用Connection对象
public boolean validateTableNameExist(String tableName) {
         Connection con = getYourCnnection;
         ResultSet rs = con.getMetaData().getTables(null, null, tableName, null);
         if (rs.next()) {
               return true;
         }else {
               return false;
         }
     }
附录: 附录:
1、 检查某表中是否存在某个字段,注意大写 1、 检查某表中是否存在某个字段,注意大写
select count(*) from User_Tab_Columns where  table_name=TABLENAME and column_name=COLUMNNAME;
select count(*) from User_Tab_Columns where table_name=TABLENAME and column_name=COLUMNNAME;
 2、 检查某内,是否存在某张表,注意表名要大写 2、 检查某内,是否存在某张表,注意表名要大写
select count(*) from all_tables where table_name=TABLENAME;
select count(*) from all_tables where table_name=TABLENAME;
public boolean validateTableNameExist(String tableName) { Connection con = getYourCnnection; ResultSet rs = con.getMetaData().getTables(null, null, tableName, null); if (rs.next()) { return true; }else { return false; } } 附录: 1、 检查某表中是否存在某个字段,注意大写 select count(*) from User_Tab_Columns where table_name=TABLENAME and column_name=COLUMNNAME; 2、 检查某内,是否存在某张表,注意表名要大写 select count(*) from all_tables where table_name=TABLENAME;
经验分享 程序员 微信小程序 职场和发展