JTDS 是開源的 SQL Server JDBC 驅動程式,效能優於微軟官方驅動且支援完整 JDBC 3.0 規格。本文提供完整 JSP 連線範例,涵蓋驅動載入、連線池建立、查詢執行與中文編碼處理。
<%@ page import="java.sql.*, java.util.*, net.sourceforge.jtds.jdbc.Driver" contentType="text/html;charset=Big5" %>
<html><head><title>JTDS 測試</title></head><body>
<%
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 1. 載入驅動 (JTDS 1.2+ 可省略 Class.forName)
Class.forName("net.sourceforge.jtds.jdbc.Driver");
// 2. 建立連線 - 建議使用連線池 (如 DBCP, HikariCP)
String dbUrl = "jdbc:jtds:sqlserver://localhost:1433/J2EEone;user=sa;password=caicaibao;charset=Big5";
con = DriverManager.getConnection(dbUrl);
// 3. 執行查詢
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT id, name, title, price FROM books");
// 4. 輸出結果
out.println("<table border='1' width='400'><tr><th>ID</th><th>Name</th><th>Title</th><th>Price</th></tr>");
while (rs.next()) {
// JTDS 1.2+ 直接 getString 即可正確處理編碼,無需手動 ISO8859-1 轉碼
out.println("<tr><td>" + rs.getString(1) + "</td><td>" + rs.getString(2)
+ "</td><td>" + rs.getString(3) + "</td><td>" + rs.getString(4) + "</td></tr>");
}
out.println("</table>");
} catch (Exception e) {
out.println("錯誤: " + e.getMessage());
e.printStackTrace();
} finally {
// 5. 關鍵:務必關閉資源,避免洩漏
try { if (rs != null) rs.close(); } catch (Exception ignore) {}
try { if (stmt != null) stmt.close(); } catch (Exception ignore) {}
try { if (con != null) con.close(); } catch (Exception ignore) {}
}
%>
</body></html>
| 參數 | 說明 | 建議值 |
|---|---|---|
| charset | 字元編碼,解決中文亂碼關鍵 | Big5 / UTF-8 / GBK |
| domain | Windows 網域驗證時指定網域 | 您的 AD 網域名 |
| instance | 命名執行個體名稱 (若非預設執行個體) | SQLEXPRESS 等 |
| useCursors | 是否使用伺服器端游標 | true (大量資料分頁時) |