問題描述
從 java 代碼中 - 我已經(jīng)連接到數(shù)據(jù)庫 - 我需要找到連接的默認(rèn)模式.
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));
}
但是,我不想要所有模式的列表.我需要此連接的默認(rèn)架構(gòu).
However, I don't want the list of all the schemas. I need the default schema of this connection.
請(qǐng)幫忙.
注意 1:我在 Windows7(開發(fā)盒)和 Linux Redhat(生產(chǎn)盒)上使用 H2 和 DB2
Note1: I am using H2 and DB2 on Windows7 (dev box) and Linux Redhat (production box)
注2:我最終得出結(jié)論,使用Java 中的Connections 對(duì)象無法使用相同的代碼找到H2 和DB2 的默認(rèn)模式.我用配置文件解決了這個(gè)問題.但是,如果有人可以分享解決方案,我可以回去重構(gòu)代碼.
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.
推薦答案
請(qǐng)使用 connection.getMetaData().getURL()
方法,該方法返回類似字符串的方法
Please use connection.getMetaData().getURL()
method which returns String like
jdbc:mysql://localhost:3306/?autoReconnect=true&useUnicode=true&characterEncoding=utf8
我們可以輕松解析它并獲取架構(gòu)名稱.它適用于所有 JDBC 驅(qū)動(dòng)程序.
We can parse it easily and get the schema name. It works for all JDBC drivers.
這篇關(guān)于如何獲取 SQL 連接的默認(rèn)模式?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!