0

From within a java code - where I already have a connection to a database - I need to find the default schema of the connection.

I have the following code that gives me a list of all schemas of that connection.

rs  = transactionManager.getDataSource().getConnection().getMetaData().getSchemas();
while (rs.next()) {
    log.debug("The schema is {} and the catalogue is {} ", rs.getString(1), rs.getString(2));
}

However, I don't want the list of all the schemas. I need the default schema of this connection.

Please help.

Note1: I am using H2 and DB2 on Windows7 (dev box) and Linux Redhat (production box)

Note2: I finally concluded that it was not possible to use the Connections object in Java to find the default schema of both H2 and DB2 using the same code. I fixed the problem with a configuration file. However, if someone can share a solution, I could go back and refactor the code.

partha
  • 2,286
  • 5
  • 27
  • 37
  • There is no JDBC API which returns the "default" (or even "current" schema). We need to know which DBMS you are using? Oracle? Postgres? –  Nov 27 '13 at 09:31
  • 2
    On `H2DB` you can issue the following query `SELECT * FROM INFORMATION_SCHEMA.SESSION_STATE WHERE KEY='SCHEMA_SEARCH_PATH'` (see: http://stackoverflow.com/questions/10141739/how-to-view-current-schema-search-path-in-a-h2-database). On DB2 `VALUES CURRENT SCHEMA` – Alex Nov 27 '13 at 10:17
  • @Alex You should put this answer in the answer's part, and not here in the comments. – AngocA Nov 27 '13 at 10:39
  • @AngocA I know, I was just passing by – Alex Nov 27 '13 at 14:03
  • What platform (OS) is your DB2 server running on? – WarrenT Dec 01 '13 at 23:14

1 Answers1

0

Please use connection.getMetaData().getURL() method which returns String like

jdbc:mysql://localhost:3306/?autoReconnect=true&useUnicode=true&characterEncoding=utf8

We can parse it easily and get the schema name. It works for all JDBC drivers.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183