java.lang.NullPointerException
at com.wgh.tools.ConnDB.executeQuery(ConnDB.java:56)
at com.wgh.dao.DiaryDao.queryDiary(DiaryDao.java:28)
at com.wgh.servlet.DiaryServlet.listAllDiary(DiaryServlet.java:249)
第 56 行:stmt = conn.createStatement(...) 拋出 NPE,代表 conn 為 null。
getConnection() 方法在取得連線失敗(驅動未載入、URL 錯誤、認證失敗、資料庫服務未啟動)時回傳 null 或拋出異常被 catch 吞掉,導致後續使用 null 連線。
public ResultSet executeQuery(String sql) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = getConnection();
if (conn == null) {
throw new SQLException("Failed to obtain database connection");
}
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(sql);
} catch (SQLException ex) {
// 記錄完整堆疊,勿只印訊息
ex.printStackTrace();
// 可選:拋出自訂異常讓上層處理
throw new RuntimeException("DB query failed", ex);
}
return rs; // 呼叫端需在 finally 關閉 rs、stmt、conn
}
try-with-resources 自動關閉資源(JDBC 4.1+)。