How to get the default schema of a SQL connection?

拟墨画扇 提交于 2019-12-02 14:29:17

问题


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.



来源:https://stackoverflow.com/questions/20238520/how-to-get-the-default-schema-of-a-sql-connection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!