SqlCredential 類別

定義

SqlCredential 提供更安全的方法,以指定使用 SQL Server 驗證的登入密碼。

SqlCredential 由將用於 SQL Server 驗證的使用者識別碼和密碼組成。 SqlCredential 物件中的密碼是 SecureString 型別。

SqlCredential 無法被繼承。

Windows 驗證 (Integrated Security = true) 會維持最安全的方式,來登入 SQL Server 資料庫。

public ref class SqlCredential sealed
public sealed class SqlCredential
type SqlCredential = class
Public NotInheritable Class SqlCredential
繼承
SqlCredential

備註

用來 Credential 取得或設定連接的物件 SqlCredential 。 使用 ChangePassword 來變更 物件的密碼 SqlCredential 。 如需物件如何影響 SqlCredential 連接集區行為的資訊,請參閱SQL Server連線共用 (ADO.NET)

InvalidOperationException如果非 Null SqlCredential 物件用於與下列任一連接字串關鍵字的連線中,將會引發例外狀況:

  • Integrated Security = true

  • Password

  • User ID

下列範例會使用 Credential 連接到 SQL Server 資料庫:

// change connection string in the APP.CONFIG file  
<connectionStrings>  
  <add name="MyConnString"  
       connectionString="Initial Catalog=myDB;Server=myServer"  
       providerName="Microsoft.Data.SqlClient" />  
</connectionStrings>  

// then use the following snippet:  
using System.Configuration;  

System.Windows.Controls.TextBox txtUserId = new System.Windows.Controls.TextBox();  
System.Windows.Controls.PasswordBox txtPwd = new System.Windows.Controls.PasswordBox();  

Configuration config = Configuration.WebConfigurationManager.OpenWebConfiguration(Null);  
ConnectionStringSettings connString = config.ConnectionStrings.ConnectionString["MyConnString"];  

using (SqlConnection conn = new SqlConnection(connString.ConnectionString))  
{  
    SecureString pwd = txtPwd.SecurePassword;  
    pwd.MakeReadOnly();  
    SqlCredential cred = new SqlCredential(txtUserId.Text, pwd);  
    conn.Credential = cred;  
    conn.Open();  
}

建構函式

SqlCredential(String, SecureString)

建立類型為 SqlCredential 的物件。

屬性

Password

取得 SqlCredential 物件的密碼元件。

UserId

取得 SqlCredential 物件的使用者識別碼元件。

適用於