How to get the default schema of a SQL connection?

2019-03-03 19:21发布

问题:

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.

回答1:

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.



标签: java sql db2 h2