我在数据库中有很多表,但我想从某些特定表中检索数据
我这样做是这样的:
DatabaseMetaData md = conn.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
System.out.println(rs.getString(3));
}
但由此我得到了数据库中存在的所有表。但我只想检索一些具有特定模式的表。模式是这样的
a_employee_raw
a_employee2_raw
b_employee_raw
b_employee2_raw
还想检查这些表是否包含数据。请提出建议。
最佳答案
你查过the documentation of DatabaseMetaData.getTables
吗? ?它说:
tableNamePattern
- a table name pattern; must match the table name as it is stored in the database
DatabaseMetaData
的介绍文本写道:
Some
DatabaseMetaData
methods take arguments that are String patterns. These arguments all have names such asfooPattern
. Within a pattern String, "%
" means match any substring of 0 or more characters, and "_
" means match any one character. Only metadata entries matching the search pattern are returned. If a search pattern argument is set tonull
, that argument's criterion will be dropped from the search.
换句话说,它的行为类似于LIKE
搜索。假设您的特定数据库以大写形式存储表名(检查 storesUpperCaseIdentifiers()
和元数据中的 friend ),您可以使用以下内容:
md.getTables(null, null, "__EMPLOYEE%_RAW", null);
这可能会匹配得更宽一点,因为第二个和第三个 _
将匹配任何字符而不仅仅是文字下划线,并且 %
将匹配数字以外的内容.
如果您的数据库默认以小写形式存储表(或者如果创建的这些表被引用并且实际上以小写形式存储),那么您需要使用:
md.getTables(null, null, "__employee%_raw", null);
请注意,最好使用以下方法来解决比文字下划线 (_
) 更宽的匹配问题
md.getTables(null, null, "_\\_EMPLOYEE%\\_RAW", null);
但我不确定是否所有 JDBC 驱动程序实际上都支持模式中的 SQL LIKE
-转义。
关于java - 从数据库中检索一些特定的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46546354/