JDBC (Java Database Connectivity) 為 Java 存取關聯式資料庫的標準 API,位於 java.sql 與 javax.sql 套件。核心四大介面:
Class.forName("oracle.jdbc.driver.OracleDriver")DriverManager.getConnection(url, user, pwd)conn.createStatement() 或 conn.prepareStatement(sql)executeQuery() (查詢) / executeUpdate() (增刪改)while(rs.next()) { rs.getInt(1); ... }rs.close(); stmt.close(); conn.close(); (逆序關閉,放在 finally 區塊)? 佔位符防止 SQL 注入。setTimestamp(idx, new Timestamp(date.getTime()));CLOB 視為 String 處理。# MySQL
jdbc.driver_class=com.mysql.jdbc.Driver
jdbc.connection.url=jdbc:mysql://192.168.9.223:3306/test_2016?useUnicode=true&characterEncoding=utf-8
jdbc.connection.username=root
jdbc.connection.password=ablejava
public class ConfigManager {
private static ConfigManager instance;
private Properties props = new Properties();
private ConfigManager() {
try (InputStream in = getClass().getClassLoader().getResourceAsStream("database.properties")) {
props.load(in);
} catch (IOException e) { e.printStackTrace(); }
}
public static ConfigManager getInstance() {
if (instance == null) instance = new ConfigManager();
return instance;
}
public String getString(String key) { return props.getProperty(key); }
}
public class BaseDao {
protected Connection conn;
protected PreparedStatement ps;
protected ResultSet rs;
public boolean getConnection() {
String driver = ConfigManager.getInstance().getString("jdbc.driver_class");
String url = ConfigManager.getInstance().getString("jdbc.connection.url");
String user = ConfigManager.getInstance().getString("jdbc.connection.username");
String pwd = ConfigManager.getInstance().getString("jdbc.connection.password");
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, user, pwd);
return true;
} catch (Exception e) { e.printStackTrace(); return false; }
}
// 通用增刪改
public int executeUpdate(String sql, Object[] params) {
int rows = 0;
if (getConnection()) {
try {
ps = conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) ps.setObject(i+1, params[i]);
rows = ps.executeUpdate();
} catch (SQLException e) { e.printStackTrace(); }
}
return rows;
}
// 通用查詢
public ResultSet executeQuery(String sql, Object[] params) {
if (getConnection()) {
try {
ps = conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) ps.setObject(i+1, params[i]);
rs = ps.executeQuery();
} catch (SQLException e) { e.printStackTrace(); }
}
return rs;
}
public boolean closeResource() {
try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); return false; }
try { if (ps != null) ps.close(); } catch (SQLException e) { e.printStackTrace(); return false; }
try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); return false; }
return true;
}
}
// EmpDao.java
public interface EmpDao {
void empList(); // 查詢全部
void add(int empno, String ename, ...); // 新增
void delete(int empno); // 刪除
void update(int empno, String ename); // 修改
}
// EmpDaoImpl.java
public class EmpDaoImpl extends BaseDao implements EmpDao {
public void empList() {
String sql = "select * from emp";
try {
ResultSet rs = executeQuery(sql, new Object[]{});
while (rs.next()) {
// 映射到 Emp 物件並列印
}
} catch (SQLException e) { e.printStackTrace(); }
finally { closeResource(); }
}
// add/delete/update 同理使用 executeUpdate
}
DataSource 負責獲取連線;連接池 管理連線生命週期 (創建、複用、銷毀),兩者職責不同。
<Resource name="jdbc/orcl" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="scott" password="orcl"
driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:orcl"/>
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/orcl");
Connection conn = ds.getConnection();
| 層次 | 職責 | 典型技術 |
|---|---|---|
| 表示層 (View) | 資料呈現、用戶交互 | JSP, HTML, JavaScript, JSTL/EL |
| 控制層 (Controller) | 接收請求、協調業務、頁面導向 | Servlet, Spring MVC @Controller |
| 業務邏輯層 (Service/BO) | 封裝業務規則、事務控制 | Service 介面/實作, @Transactional |
| 資料訪問層 (DAO) | CRUD、資料源操作 | Dao 介面/實作, JdbcTemplate, MyBatis |
<jsp:useBean id="service" class="com.service.Impl" scope="page/request/session/application"> 實例化 Bean。<jsp:setProperty name="service" property="dao" value="<%=dao%>"> 依賴注入。<%@ include file="top.jsp" %> (編譯期合併,被包含頁變動需重編譯)。<jsp:include page="url"> (運行期合併結果,被包含頁變動無需重編譯)。<jsp:forward page="url"> (同 RequestDispatcher.forward)。永遠使用 PreparedStatement 參數化查詢,切勿拼接 SQL 字串。惡意輸入範例:a' or 1=1 --。