連接字串看似簡單,卻藏著許多同義詞、預設值陷阱與安全隱患。本文系統梳理核心關鍵字、驗證模式選擇、ADO.NET 實戰範例,助你寫出正確、安全、可維護的連接字串。
| 關鍵字 (別名) | 說明 | 備註 |
|---|---|---|
| Data Source / Server / Address / Addr / Network Address | 伺服器位址:IP、主機名、實例名 (如 `localhost\SQLEXPRESS`)、`(local)` | 必填 |
| Initial Catalog / Database | 預設資料庫名 | 兩者完全等價,擇一使用 |
| User ID / UID | SQL 認證帳號 | 搭配 Password 使用 |
| Password / PWD | SQL 認證密碼 | 含特殊字元需逸出 |
| Integrated Security / Trusted_Connection | Windows 整合驗證:`true/yes/SSPI` 啟用,`false/no` 關閉 | 強烈建議 SSPI,啟用時忽略 UID/PWD |
| Persist Security Info | 是否在連接開啟後允許透過屬性取得密碼 | 預設 `false` (安全),勿改 `true` |
| Connect Timeout / Connection Timeout | 連線逾時秒數 | 預設 15 秒,網路不穩可調大 |
| Encrypt | 強制 TLS 加密傳輸 | `true` 需伺服器有效憑證 |
| TrustServerCertificate | 信任伺服器憑證 (跳過驗證) | 開發/測試環境配合 Encrypt=true 使用 |
| Application Name | 應用程式名稱,顯示於 `sys.dm_exec_sessions` | 利於 DBA 追蹤與資源管控 |
| MultipleActiveResultSets (MARS) | 單一連接支援多個作用中結果集 | 預設 `false`,Entity Framework 常需 `true` |
| Pooling | 連接池啟用 | 預設 `true`,極少關閉 |
| Min Pool Size / Max Pool Size | 連接池上下限 | 高併發可調大 Max (預設 100) |
Server=(local);Database=Northwind;Integrated Security=SSPI;
Server=192.168.0.1;Database=MyDB;User ID=sa;Password=Str0ngP@ss;Persist Security Info=False;
// 1. 本地預設實例 + 整合驗證
"Server=(local);Integrated Security=SSPI;Database=Pubs;"
// 2. 本地命名實例 + 整合驗證
"Server=(local)\NetSDK;Database=pubs;Integrated Security=SSPI;"
// 3. 完整參數 + 應用名稱 + 連接池調整
"Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;Application Name=MyApp;Min Pool Size=5;Max Pool Size=200;"
// 4. 遠端 IP + SQL 驗證 + 逾時 + 加密
"Data Source=127.0.0.1;Initial Catalog=pubs;User ID=sa;Password=passwords;Connect Timeout=30;Encrypt=True;TrustServerCertificate=False;"
// 5. 具名管道 (本機高效能)
"Server=np:\\.\pipe\MSSQL$SQLEXPRESS\sql\query;Integrated Security=SSPI;Database=Northwind;"
var builder = new SqlConnectionStringBuilder
{
DataSource = "localhost",
InitialCatalog = "MyDB",
IntegratedSecurity = true,
ApplicationName = "MyApp",
Encrypt = true
};
string connStr = builder.ConnectionString;