Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get database schema name when using oracle jdbc connection?

Tags:

java

oracle

jdbc

I am trying to get all db tables using DatabaseMetaData.getTables() method. But this method requires database schema name pattern. Is it possible to get schema name for current db connection?

like image 697
johnny-b-goode Avatar asked Nov 12 '12 09:11

johnny-b-goode


2 Answers

The standard schema for your current connection is the name of the user you use to log in. So if your user is SCOTT you have to use SCOTT for DatabaseMetaData.getTables().

You can obtain the username through DatabaseMetaData.getUserName().

But remember that the comparison of schema/username done in the JDBC driver is case-sensititve and normally usernames are in uppercase.

I am not 100% sure if DatabaseMetaData.getUserName() will return the name in the correct case in all situations. To be sure, you might want to do an upperCase() before using that value.

like image 184
a_horse_with_no_name Avatar answered Oct 28 '22 17:10

a_horse_with_no_name


Try to play with getCatalogs(). This is a quick draft

  public List<String> getDatabases(DBEnv dbEnv) {

        Connection conn = getConnection(dbEnv);
        List<String> resultSet = new ArrayList<String>();

        try {
            DatabaseMetaData metaData = conn.getMetaData();
            ResultSet res = metaData.getCatalogs();

            while (res.next()) {
                resultSet.add(res.getString("TABLE_CAT"));
            }

        } catch (SQLException e) {
            logger.error(e.toString());
        }

        return resultSet;

    }
like image 23
Thai Tran Avatar answered Oct 28 '22 18:10

Thai Tran