SQL Server 客戶端連接不僅需 DLL,還依賴:
| 文件 | 來源 | 用途 | 必選 |
|---|---|---|---|
| `sqlncli10.dll` / `sqlncli11.dll` / `msodbcsql17.dll` / `msoledbsql.dll` | SQL Native Client / ODBC Driver / OLE DB Driver 安裝包 | 現代首選數據訪問提供程序 (TDS 8.0+、加密、MARS、TVP) | ✅ |
| `dbnetlib.dll` | SQL Server 安裝介質 / 系統目錄 | TCP/IP Named Pipes 兼容層 (舊應用) | ⚠️ 僅舊應用 |
| `ntwdblib.dll` (2000.80.x) | SQL Server 2000 介質 | DB-Library 極舊應用 (PB/Delphi/VB6) | ⚠️ 極舊應用 |
| CRT 運行庫 (vc_redist.x86/x64.exe) | Microsoft 官網 | 所有 DLL 依賴基礎 | ✅ |
無需寫入 `HKLM\...\ConnectTo`,直接在連接字串指定協議與端口:
-- TCP/IP 直連 (推薦)
Server=tcp:192.168.1.100,1433;Database=MyDB;Uid=User;Pwd=Secret;Encrypt=TrustServerCertificate;
-- Named Pipes (內網低延遲)
Server=np:\\DBServer\pipe\sql\query;Database=MyDB;Trusted_Connection=yes;
-- 別名 (需客戶端配置別名或 SQL Native Client 支持)
Server=MyAlias;Database=MyDB;...
#Requires -RunAsAdministrator
param($TargetDir = "C:\App\Bin")
# 1. 確保 VC++ Redist
if (-not (Test-Path "HKLM:\SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64")) {
Write-Host "Installing VC++ 2015-2022 Redist..." -Fore Yellow
Start-Process -Wait -FilePath "vc_redist.x64.exe" -ArgumentList "/install", "/quiet", "/norestart"
}
# 2. 複製核心 DLL (假設已放在腳本目錄下 \Dlls)
$Dlls = @("sqlncli11.dll","msodbcsql17.dll","msoledbsql.dll","dbnetlib.dll")
foreach ($d in $Dlls) {
if (Test-Path ".\Dlls\$d") {
Copy-Item ".\Dlls\$d" -Destination $TargetDir -Force
Write-Host "Copied $d"
}
}
# 3. 驗證連接 (需引用 System.Data.dll)
Add-Type -AssemblyName System.Data
$cs = "Server=tcp:192.168.1.100,1433;Database=master;Uid=sa;Pwd=Test123;Connect Timeout=5;Encrypt=TrustServerCertificate;"
try {
$conn = New-Object System.Data.SqlClient.SqlConnection $cs
$conn.Open()
Write-Host "Connection OK, ServerVersion: $($conn.ServerVersion)" -Fore Green
$conn.Close()
} catch {
Write-Host "Connection FAILED: $($_.Exception.Message)" -Fore Red
}
| 錯誤信息 | 根因 | 修復 |
|---|---|---|
| `Provider not found. It may not be properly installed.` | OLE DB/ODBC 驅動未安裝/註冊 | 安裝 `MSOLEDBSQL.msi` / `msodbcsql.msi` 或複製 DLL + `regsvr32` (OLE DB) |
| `SQL Network Interfaces: Error 26 - Error Locating Server/Instance Specified` | 實例名錯誤/瀏覽器服務未啟動/防火牆 | 用 `tcp:IP,Port` 直連、啟動 SQL Browser、開放 1434 UDP |
| `The client and server cannot communicate, because they do not possess a common algorithm` | TLS 版本不匹配 (客戶端舊、服務器強制 TLS 1.2+) | 更新驅動至最新、啟用 `Encrypt=TrustServerCertificate`、或服務器降級 TLS |
| `LoadLibrary failed for sqlncli11.dll` | 位數不匹配 (x86 進程載入 x64 DLL 或反向) | 編譯目標平台與 DLL 位數一致、或安裝雙版本驅動 |