我知道如何使用.getTables()
来获取TABLE
和ALIAS
条目。
final ResultSet rs = dmd.getTables(null, "MySchema", "%", new String[]{"TABLE","ALIAS"});
我需要确定哪个ALIAS
与哪个TABLE
名称相关?
我特别需要能够在Oracle
,SQL Server
和DB2
上执行此操作。
鉴于我有一个表格T00001
,其别名为MyTable
,如何使用DatabaseMetaData
来电中的Connection.getMetaData()
来匹配这两个?
答案 0 :(得分:1)
在查看JDBC API和oracle.jdbc.OracleDatabaseMetaData之后,我非常确定在使用库存Oracle JDBC驱动程序时无法通过DatabaseMetaData直接检索此信息。 DB2或SQL Server可能存在特定于驱动程序的方法,因为我没有彻底检查它们。作为作弊,您可以从DatabaseMetaData对象getConnection()
运行特定于数据库的查询以检索所需的信息,如下所示:
public class TableAliasMapperJdbc {
public Map<String, List<String>> mapTableAliases(String url, String user, String password, String sql) throws SQLException {
try (
Connection conn = DriverManager.getConnection(url, user, password);
// we use conn.getMetaData().getConnection() instead of conn here only to fit within the parameters of the question
PreparedStatement stmt = conn.getMetaData().getConnection().prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
) {
// this may not do what you want if you have synonyms of synonyms
Map<String, List<String>> tableAliases = new HashMap<>();
while (rs.next()) {
String table = rs.getString(1);
String alias = rs.getString(2);
List<String> aliases = tableAliases.get(table);
if (aliases == null) {
tableAliases.put(table, aliases = new ArrayList<>(2));
}
aliases.add(alias);
}
return tableAliases;
}
}
public void print(String dbName, Map<String, List<String>> tableAliases) {
System.out.format("\nThe following are the table aliases for %s:\n", dbName);
for (Map.Entry<String, List<String>> entry : tableAliases.entrySet()) {
System.out.format("The alias(es) for %s are: %s.\n", entry.getKey(), String.join(", ", entry.getValue()));
}
}
public static void main(String[] args) throws SQLException {
TableAliasMapperJdbc mapper = new TableAliasMapperJdbc();
mapper.print("Oracle",
mapper.mapTableAliases(
"jdbc:oracle:thin:@localhost:1521:xe",
"scott",
"tiger",
"SELECT table_name, synonym_name FROM user_synonyms")); // or maybe all_synonyms
mapper.print("DB2",
mapper.mapTableAliases(
"jdbc:db2://localhost:50000/SAMPLE",
"db2admin",
"db2admin",
"SELECT base_tabname, tabname FROM syscat.tables WHERE type = 'A' AND owner = 'DB2ADMIN'"));
mapper.print("SQL Server",
mapper.mapTableAliases(
"jdbc:sqlserver://localhost:1433",
"sa",
"Password123",
"SELECT PARSENAME(base_object_name,1), name FROM sys.synonyms"));
}
}
使用JDK 1.8.0_45,Oracle XE 11.2.0.2.0及其捆绑的JDBC驱动程序DB2 Express-C 10050500及其捆绑的JDBC驱动程序以及带有Microsoft JDBC Driver 4.1的SQL Server 2014 Express 12.0.2000.8成功测试了代码.5605.100。
<子> 基于http://sqlblog.com/blogs/john_paul_cook/archive/2010/08/24/script-to-list-synonym-contents.aspx的SQL Server查询。 子>