首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> SQL Server 資料庫 >> 關於SqlServer

C# 連接 SQL Server 連接字串大全與最佳實務

     編輯:關於SqlServer

SqlConnection 連接字串完整速查表

連接字串是 ADO.NET 應用與 SQL Server 溝通的鑰匙。本文整理最常見的 6 類連接模式、關鍵參數深度解析、SqlConnectionStringBuilder 強型別建構法、Visual Studio 設計工具生成法,並附上完整可執行範例。

一、六大經典連接字串模板

場景連接字串範例說明
標準 SQL 驗證Data Source=myServer;Initial Catalog=myDB;User Id=usr;Password=pwd;最通用,跨網域、容器皆適用
指定埠號與網路庫Data Source=192.168.1.100,1433;Network Library=DBMSSOCN;Initial Catalog=myDB;User ID=usr;Password=pwd;強制 TCP/IP,繞過命名管道
簡寫別名Server=myServer;Database=myDB;User ID=usr;Password=pwd;Trusted_Connection=False;Server=Data Source,Database=Initial Catalog
Windows 整合驗證Server=myServer;Database=myDB;Trusted_Connection=True;當前 Windows 身分登入,無需帳密
具名實例 + 整合驗證Server=myServer\\Instance;Database=myDB;Trusted_Connection=True;雙反斜線或 @\"Server\\Instance\"
SSPI (推薦整合驗證寫法)Data Source=myServer;Initial Catalog=myDB;Integrated Security=SSPI;SSPI 等同 True,相容性最佳

二、關鍵參數深度解析

1. Integrated Security / Trusted_Connection

  • True / SSPI:啟用 Windows 整合驗證,**忽略** 字串中的 User ID/Password。
  • False(預設):使用 SQL Server 驗證,**必須** 提供 User ID/Password。
  • 建議:統一使用 Integrated Security=SSPI,避免大小寫/拼字差異。

2. Initial Catalog

指定預設資料庫名稱,等同 Database。連接後可用 USE [OtherDB] 切換。

3. 其他實用參數

  • Connection Timeout=30:連線逾時秒數(預設 15)。
  • Max Pool Size=100:連線池上限,高併發調大。
  • Encrypt=True;TrustServerCertificate=False;:強制 TLS 加密(Azure SQL 必須)。
  • Application Name=MyApp:SQL Profiler / DMV 易於識別來源。

三、強型別建構:SqlConnectionStringBuilder

避免字串拼接錯誤、智慧提示完整、自動處理逸出字元:

var scsb = new SqlConnectionStringBuilder {
    DataSource = @"(local)\\SQLEXPRESS",
    InitialCatalog = "Northwind",
    IntegratedSecurity = true,  // 或 SSPI
    // UserID = "usr", Password = "pwd", // SQL 驗證時啟用
    ConnectTimeout = 30,
    ApplicationName = "OrderSystem"
};
using (var conn = new SqlConnection(scsb.ConnectionString)) {
    conn.Open();
    // ...
}

四、Visual Studio 設計工具生成(零記憶)

  1. 專案屬性 → Settings → 新增 ConnectionString 型別設定。
  2. 點選值欄位下拉 → 新增連接 → 選擇 Microsoft SQL Server。
  3. 輸入伺服器名(本機用 (local)\\SQLEXPRESS)、驗證方式、資料庫名 → 測試連接 → 確定。
  4. 自動生成 app.config/web.config 內 <connectionStrings> 區段。
  5. 程式碼取用:ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString

五、完整可執行測試範例

using System;
using System.Data;
using System.Data.SqlClient;

namespace ConnectDB {
    class Program {
        static void Main() {
            const string connStr = "Data Source=ServerName;Initial Catalog=DatabaseName;Integrated Security=SSPI";
            using (var sqlCon = new SqlConnection(connStr))
            using (var cmd = new SqlCommand("SELECT TOP 5 * FROM Customers", sqlCon))
            using (var adapter = new SqlDataAdapter(cmd)) {
                sqlCon.Open();
                var ds = new DataSet();
                adapter.Fill(ds);
                Console.WriteLine(ds.GetXml());  // 輸出 XML 驗證
            }
            Console.ReadKey();
        }
    }
}

六、避坑清單

  • ❌ 字串中包含 ; 或 = 的密碼未加雙引號 → 解析錯誤。
  • ❌ Integrated Security=True 仍保留 User ID → 被忽略,易誤以為權限不足。
  • ❌ 連接字串寫死在程式碼 → 部署環境切換痛苦,務必外部化設定檔/Key Vault。
  • ✅ 使用 SqlConnectionStringBuilder 或設計工具生成。
  • ✅ 正式環境啟用 Encrypt=True。

掌握這些模板與工具,連接字串不再是 Bug 溫床,而是穩定高效的資料通道。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved