我用以下代碼用來(lái)測(cè)試數(shù)據(jù)庫(kù)連接是否正常:
try {
logger.info("start to registerDriver...");
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
logger.info(pros.getProperty("dbURL")+"--"+pros.getProperty("user")+"--"+ pros.getProperty("password"));
con = DriverManager.getConnection(pros.getProperty("dbURL"), pros.getProperty("user"), pros.getProperty("password"));;
if (con != null) {
st = con.createStatement();
rs = st.executeQuery("select 1 from dual");
rs.next();
if (rs.getInt(1) == 1) {
res = true;
}
}
}
然后我做了一個(gè)java application桌面小應(yīng)用程序(extends FrameView),在小應(yīng)用程序中點(diǎn)擊事件觸發(fā)此段代碼,如下:
private void dbTestMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
//從配置文件中讀取連接相關(guān)屬性
String info = "數(shù)據(jù)庫(kù)連接異常,請(qǐng)確認(rèn)配置文件是參數(shù)是否正確。";
Properties per = new Properties();
try {
logger.info("start to test the db connection...");
per.load(new FileInputStream(Content.configFile));
logger.info("system have loaded the config files successfully");
DbOper db = new DbOper();
if (db.checkDBConnect(per)) {
info = "數(shù)據(jù)庫(kù)連接正常";
}
logger.info("數(shù)據(jù)連接測(cè)試結(jié)果:" + info);
} catch (Exception e) {
logger.error("Exception when test the DB connection, ",e);
}
if (aboutBox == null) {
JFrame mainFrame = AnalyseExcelApp.getApplication().getMainFrame();
aboutBox = new DBTestResultBox(mainFrame, info);
aboutBox.setLocationRelativeTo(mainFrame);
}
AnalyseExcelApp.getApplication().show(aboutBox);
}
但在運(yùn)行時(shí),程序頭也不回地直接死了,調(diào)試時(shí)發(fā)現(xiàn)程序是在
con = DriverManager.getConnection(pros.getProperty("dbURL"), pros.getProperty("user"), pros.getProperty("password"));;
這一行,不行了,也不報(bào)錯(cuò),就直接在此行一直呆著,啥也不做...
另外還有二種情況,也讓我比較奇怪:
1. 若同樣調(diào)用此段測(cè)試代碼,但不是在java application中,而是直接在一個(gè)普通的java類的main方法中,測(cè)可以測(cè)試通過(guò)。
2. 若數(shù)據(jù)庫(kù)邊的是本機(jī)的數(shù)據(jù)庫(kù),那么此段測(cè)試代碼也可以通過(guò),在java application與java類的main方法中均可以。
為什么,連接遠(yuǎn)程數(shù)據(jù)時(shí),在java application中會(huì)無(wú)故down掉呢?
ps. 排除數(shù)據(jù)庫(kù)地址,用戶名,密碼等錯(cuò)誤;我的JDBC驅(qū)動(dòng)是ojdbc14.jar,JDK 1.5