SQL Server 2012 預設**停用 TCP/IP 協定**且使用**動態埠**,導致 Java JDBC 無法連線。本文提供逐步圖文指引:切換至 SQL Server 驗證模式、啟用 TCP/IP、固定埠 1433、防火牆設定、telnet 驗證、JDBC 連線測試,一氣呵成。
SQL Server 2012 安裝時若選 **Windows 驗證模式**,需切換為 **混合模式 (SQL Server 和 Windows)**:
sa → 屬性 → 狀態 → **授予** + **啟用** → 設定強密碼。MSSQLSERVER 的協定) → 右側:
127.0.0.1、**Enabled** 設為 **Yes**。cmd → 執行:telnet localhost 1433 (或 telnet 192.168.x.x 1433)。quit 離開)。// 標準連線 (jTDS 驅動較舊,建議用 Microsoft 官方驅動 sqljdbc42.jar)
String url = "jdbc:sqlserver://localhost:1433;databaseName=YourDB;user=sa;password=YourPass;";
// 若使用具名執行個體 (如 SQLEXPRESS)
String urlNamed = "jdbc:sqlserver://localhost;instanceName=SQLEXPRESS;databaseName=YourDB;user=sa;password=YourPass;";
// 關鍵參數建議
String urlFull = "jdbc:sqlserver://192.168.1.50:1433;databaseName=MyDB;user=app_user;password=P@ssw0rd;"
+ "encrypt=true;trustServerCertificate=true;"
+ "applicationName=MyJavaApp;"
+ "sendStringParametersAsUnicode=false;";
import java.sql.*;
public class TestSql2012 {
public static void main(String[] args) {
String url = "jdbc:sqlserver://localhost:1433;databaseName=TestDB;user=sa;password=123456;";
try (Connection conn = DriverManager.getConnection(url)) {
System.out.println("✅ 連線成功! Catalog: " + conn.getCatalog());
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT @@VERSION")) {
if (rs.next()) System.out.println("版本: " + rs.getString(1));
}
} catch (SQLException e) {
System.err.println("❌ 連線失敗: " + e.getMessage());
e.printStackTrace();
}
}
}
| 現象 | 可能原因 | 解決 |
|---|---|---|
| telnet 連不上 | TCP/IP 未啟用 / 埠非 1433 / 防火牆 / 服務未重啟 | 依本文步驟逐項檢查 |
| Login failed for user 'sa' | sa 未啟用 / 密碼錯誤 / 驗證模式非混合模式 | SSMS 啟用 sa、重設密碼、確認混合模式 |
| The TCP/IP connection to the host has failed | JDBC URL host/port 錯誤、IPv6 優先導致解析異常 | URL 使用 IPv4 位址、加 -Djava.net.preferIPv4Stack=true |
| Driver class not found | sqljdbc42.jar 未在 Classpath | Maven/Gradle 引入或手動加入 Build Path |
照著步驟操作,SQL Server 2012 遠端連線一次成功,告別反覆試錯。