問題情況
由于PostgreSQL數(shù)據(jù)庫模式(schema)存在多個,原先的表單是默認采用public但是查詢表和字段時候有查詢所有未進行過濾,導致數(shù)據(jù)庫連接失敗、查表字段也為空(空即查詢服務端異常錯誤)
解決方式
- 數(shù)據(jù)庫連接配置
添加參數(shù)補充?currentSchema=dwd
譬如:username=root;password=XXXX;url=jdbc:postgresql://11.XX.XX.145:5432/test_data?currentSchema=dwd
代碼優(yōu)化
代碼調(diào)整
首先獲取url:文章來源:http://www.zghlxwxcb.cn/news/detail-505231.html
jdbc:postgresql://localhost:5432/test_data?currentSchema=dwd ==> 解析【currentSchema=dwd】
jdbc:postgresql://localhost:5432/test_data?currentSchema=public ==> 解析【currentSchema=public】
jdbc:postgresql://localhost:5432/test_data ==> 解析【currentSchema=null】默認表使用【current_schema()】表字段查詢使用【public】
然后根據(jù)解析,參數(shù)傳遞查詢文章來源地址http://www.zghlxwxcb.cn/news/detail-505231.html
/**
* 解析 jdbc的url內(nèi)的默認參數(shù)
* <p>
* 譬如:username=root;password=XXXX;url=jdbc:postgresql://11.XX.XX.145:5432/test_data?currentSchema=dwd
* 獲取 currentSchema=dwd
*
* @param url
* @return
*/
public static Map<String, Object> analysisDefParam(String url) {
Map<String, Object> value = new HashMap<>();
try {
String[] params = url.split("\\?");
List<String> param = new ArrayList<>();
if (params.length > 1) {
param = Arrays.asList(params[1].split("&"));
}
param.forEach(p -> {
String[] item = p.split("=");
if (item.length > 1) {
value.put(item[0], item[1]);
}
});
} catch (Exception e) {
log.error("出現(xiàn)異常 {} {}", e);
}
return value;
}
- 其他
## 版本查看
select version();
datasource 如何指定postgresql 連接的schema
##9.4開始通過關(guān)鍵字currentSchema指定
jdbc:postgresql://localhost:5432/mypgsql?currentSchema=myschema
##舊版本通過searchpath指定 (代碼暫未兼容)
jdbc:postgresql://localhost:5432/mypgsql?searchpath=myschema
到了這里,關(guān)于【PostgreSQL】連接pg數(shù)據(jù)庫Schema切換的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!