Share via


SqlCredential 类

定义

SqlCredential 提供了更安全的方式来指定使用 SQL Server 身份验证尝试登录的密码。

SqlCredential 由用户 ID 和将用于 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 对象的用户 ID 组件。

适用于