JDBC获取ResultSet的MetaData 2

两盒软妹~` 提交于 2020-01-24 00:17:46

上一篇关于JDBC获取MetaData的文章:http://www.cnblogs.com/lyhtbc/archive/2012/03/15/jdbc_get_metadata.html

有一个关键的效率问题没有解决:全表扫描。 

 

其实可以通过DatabaseMetaData来获取,并不需要对表进行扫描。

以下是验证表或字段是否存在的方法:

 1 public abstract class DatabaseMetaDataUtil {
 2 
 3     public static boolean isTableExisted(DataSource dataSource, String table) {
 4         try {
 5             DatabaseMetaData metaData = dataSource.getConnection().getMetaData();
 6             ResultSet rs = metaData.getTables(nullnull, table, new String[] { "TABLE" });
 7             while (rs.next()) {
 8                 return true;
 9             }
10         } catch (SQLException e) {
11             // nothing to do
12         }
13         return false;
14     }
15 
16     public static boolean isFieldExisted(DataSource dataSource, String table, String field) {
17         try {
18             DatabaseMetaData metaData = dataSource.getConnection().getMetaData();
19             ResultSet rs = metaData.getColumns(nullnull, table, field);
20             if (rs.next()) {
21                 return true;
22             }
23         } catch (SQLException e) {
24             // nothing to do
25         }
26         return false;
27     }
28 
29 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!