上一篇关于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(null, null, 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(null, null, 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 }
2
3 public static boolean isTableExisted(DataSource dataSource, String table) {
4 try {
5 DatabaseMetaData metaData = dataSource.getConnection().getMetaData();
6 ResultSet rs = metaData.getTables(null, null, 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(null, null, 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 }
来源:https://www.cnblogs.com/lyhtbc/archive/2012/05/22/jdbc_get_metadata_DatabaseMetaData.html