ConnectionFactory (抽象連線取得)
↑ 繼承
DBOperater (通用 CRUD、Prepared/CallableStatement)
↑ 繼承
OracleDBOperater (Oracle XML 等特有功能)
public class ConnectionFactory {
protected Connection conn;
private static final String URL = "jdbc:mysql://...";
private static final String USER = "root";
private static final String PASS = "pwd";
public ConnectionFactory() throws SQLException {
makeConnection();
}
public void makeConnection() throws SQLException {
conn = DriverManager.getConnection(URL, USER, PASS);
}
public void close() throws SQLException {
if (conn != null && !conn.isClosed()) conn.close();
}
}
conn 為 protected,供子類存取;建構子拋出異常,強制呼叫端處理連線失敗。
public class DBOperater extends ConnectionFactory {
public ResultSet executeQuery(String sql) throws SQLException {
ensureConnection();
Statement stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
return stmt.executeQuery(sql);
}
public ResultSet executeUpdatableQuery(String sql) throws SQLException {
ensureConnection();
Statement stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
return stmt.executeQuery(sql);
}
public int executeUpdate(String sql) throws SQLException {
ensureConnection();
Statement stmt = conn.createStatement(); // 基本型別,省記憶體
return stmt.executeUpdate(sql);
}
public PreparedStatement getPreparedStmt(String sql) throws SQLException {
ensureConnection();
return conn.prepareStatement(sql);
}
public CallableStatement getCallableStmt(String sql) throws SQLException {
ensureConnection();
return conn.prepareCall(sql);
}
private void ensureConnection() throws SQLException {
if (conn == null || conn.isClosed()) makeConnection();
}
}
public class OracleDBOperater extends DBOperater {
public OracleXMLQuery getOXQuery(String sql, String table) throws Exception {
OracleXMLQuery qry = new OracleXMLQuery(conn, sql);
qry.setRowsetTag(table);
qry.setRowTag("RECORD");
return qry;
}
public int insertXML(String path, String table) throws Exception {
OracleXMLSave sav = new OracleXMLSave(conn, table);
sav.setRowTag("RECORD");
int x = sav.insertXML(sav.createURL(path));
sav.close();
return x;
}
}
這個分層結構以單一職責切分關注點:連線管理、通用 SQL、廠商擴充。下篇將介紹 DatabaseMetaData 動態探索未知資料庫結構。