JSP/Servlet 應用連線 SQL Server 需正確安裝 JDBC 驅動、設定類別路徑、啟用 TCP/IP 通訊協定、撰寫連線程式碼。本文提供從驅動下載、Tomcat 部署、SQL Server 組態、連線字串差異 (2000 vs 2005/2008+) 到 JSP 範例的完整步驟,並說明常見錯誤排除。
mssql-jdbc-12.4.2.jre11.jar)。$CATALINA_HOME/lib/,所有 Webapp 共用,利於連線池。WEB-INF/lib/,隨應用打包部署 (WAR)。CLASSPATH **不需** 設定 (Servlet 容器忽略),若為立獨 Java 應用則需加入。1433 (清空 TCP Dynamic Ports)。1433 埠 (入站規則)。| 版本 | 驅動類別 | JDBC URL 格式 |
|---|---|---|
| SQL Server 2000 | com.microsoft.jdbc.sqlserver.SQLServerDriver | jdbc:microsoft:sqlserver://host:1433;DatabaseName=DB |
| SQL Server 2005/2008/2012/2014/2016/2017/2019/2022 | com.microsoft.sqlserver.jdbc.SQLServerDriver | jdbc:sqlserver://host:1433;databaseName=DB;encrypt=true;trustServerCertificate=true |
常見錯誤:使用 2000 版驅動類別/URL 連 2005+ 會報 ClassNotFoundException 或 No suitable driver。請務必對應正確版本。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*, javax.sql.*, javax.naming.*" %>
<%@ page import="java.util.Properties" %>
<%
// 1. 連線參數 (生產環境建議從 context-param 或 JNDI 取得)
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url = "jdbc:sqlserver://localhost:1433;databaseName=mydb;encrypt=true;trustServerCertificate=true";
String user = "sa";
String pwd = "YourStrongPassword";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 2. 載入驅動 (JDBC 4.0+ 可省略,但保留相容)
Class.forName(driver);
// 3. 取得連線
conn = DriverManager.getConnection(url, user, pwd);
// 4. 執行查詢 (使用 PreparedStatement 防注入)
String sql = "SELECT id, name, email FROM Users WHERE status = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 1); // 綁定參數
rs = pstmt.executeQuery();
// 5. 處理結果
out.println("<table border='1'><tr><th>ID</th><th>Name</th><th>Email</th></tr>");
while (rs.next()) {
out.println("<tr><td>" + rs.getInt("id") + "</td>" +
"<td>" + rs.getString("name") + "</td>" +
"<td>" + rs.getString("email") + "</td></tr>");
}
out.println("</table>");
} catch (Exception e) {
out.println("<font color='red'>Error: " + e.getMessage() + "</font>");
e.printStackTrace();
} finally {
// 6. 逆序關閉資源 (Java 7+ try-with-resources 更佳)
if (rs != null) try { rs.close(); } catch (SQLException ignore) {}
if (pstmt != null) try { pstmt.close(); } catch (SQLException ignore) {}
if (conn != null) try { conn.close(); } catch (SQLException ignore) {}
}
%>
context.xml 設定全域資料源<Resource name="jdbc/MyDB"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="app_user"
password="AppUserPwd"
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url="jdbc:sqlserver://localhost:1433;databaseName=mydb;encrypt=true;trustServerCertificate=true"
validationQuery="SELECT 1"
testOnBorrow="true"
testWhileIdle="true"
timeBetweenEvictionRunsMillis="30000"
minEvictableIdleTimeMillis="60000" />
web.xml 宣告參照<resource-ref>
<description>SQL Server DataSource</description>
<res-ref-name>jdbc/MyDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/MyDB");
Connection conn = ds.getConnection();
// ... 後續同前,最後 conn.close() 歸還連線池而非真正關閉
| 錯誤 | 原因 | 解決 |
|---|---|---|
| ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver | 驅動 JAR 不在 Classpath | 放入 $CATALINA_HOME/lib 或 WEB-INF/lib |
| No suitable driver found for jdbc:sqlserver://... | URL 格式錯誤 / 驅動未註冊 | 確認驅動類別名、URL 前綴 jdbc:sqlserver:// |
| The TCP/IP connection to the host has failed | SQL Server TCP/IP 未啟用 / 埠錯誤 / 防火牆 | Configuration Manager 啟用 TCP/IP、設 1433、開防火牆 |
| Login failed for user 'sa' | 密碼錯誤 / 混合模式未啟用 / 帳號鎖定 | SSMS 登入重設密碼、啟用 SQL Server 驗證模式 |
| The driver could not establish a secure connection to SQL Server | 加密連線憑證問題 | URL 加 trustServerCertificate=true (測試環境) 或匯入正式憑證 |
掌握「驅動版本對應 URL 格式」、「TCP/IP 啟用與埠設定」、「PreparedStatement 參數化」、「JNDI 連線池整合」四大核心,即能建立穩定、安全、高效能的 JSP-SQL Server 應用。請務必避開 SQL Server 2000 版驅動類別/URL 連接新版資料庫這一經典陷阱。