SqlConnection.ChangePassword 方法   
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
更改 SQL Server 密码。
重载
| ChangePassword(String, SqlCredential, SecureString) | 更改 SqlCredential 对象中指示的用户的 SQL Server 密码。 | 
| ChangePassword(String, String) | 将连接字符串中指示的用户的 SQL Server 密码更改为提供的新密码。 | 
ChangePassword(String, SqlCredential, SecureString)
更改 SqlCredential 对象中指示的用户的 SQL Server 密码。
public:
 static void ChangePassword(System::String ^ connectionString, System::Data::SqlClient::SqlCredential ^ credential, System::Security::SecureString ^ newPassword);public:
 static void ChangePassword(System::String ^ connectionString, System::Data::SqlClient::SqlCredential ^ credential, System::Security::SecureString ^ newSecurePassword);public static void ChangePassword (string connectionString, System.Data.SqlClient.SqlCredential credential, System.Security.SecureString newPassword);public static void ChangePassword (string connectionString, System.Data.SqlClient.SqlCredential credential, System.Security.SecureString newSecurePassword);static member ChangePassword : string * System.Data.SqlClient.SqlCredential * System.Security.SecureString -> unitstatic member ChangePassword : string * System.Data.SqlClient.SqlCredential * System.Security.SecureString -> unitPublic Shared Sub ChangePassword (connectionString As String, credential As SqlCredential, newPassword As SecureString)Public Shared Sub ChangePassword (connectionString As String, credential As SqlCredential, newSecurePassword As SecureString)参数
- connectionString
- String
包含足够信息的连接字符串,用于连接到服务器。 连接字符串不应使用以下任何连接字符串关键字:Integrated Security = true、UserId或 Password;或 ContextConnection = true。
- credential
- SqlCredential
SqlCredential 对象。
- newPasswordnewSecurePassword
- SecureString
新密码。
              newPassword 必须是只读的。 密码还必须符合服务器上设置的任何密码安全策略(例如,特定字符的最小长度和要求)。
例外
连接字符串包含 UserId、Password或 Integrated Security=true的任意组合。
-或-
连接字符串包含 Context Connection=true。
-或-
              newSecurePassword(或 newPassword)大于 128 个字符。
-或-
              newSecurePassword(或 newPassword)不只读。
-或-
              newSecurePassword(或 newPassword)是空字符串。
其中一个参数(connectionString、credential或 newSecurePassword)为 null。
另请参阅
适用于
ChangePassword(String, String)
将连接字符串中指示的用户的 SQL Server 密码更改为提供的新密码。
public:
 static void ChangePassword(System::String ^ connectionString, System::String ^ newPassword);public static void ChangePassword (string connectionString, string newPassword);static member ChangePassword : string * string -> unitPublic Shared Sub ChangePassword (connectionString As String, newPassword As String)参数
- connectionString
- String
包含足够信息的连接字符串,用于连接到所需的服务器。 连接字符串必须包含用户 ID 和当前密码。
- newPassword
- String
要设置的新密码。 此密码必须符合服务器上设置的任何密码安全策略,包括最小长度、特定字符的要求等。
例外
              connectionString 或 newPassword 参数为 null。
示例
警告
Microsoft不建议直接提供用户名和密码,因为它是不安全模式。 如果可能,请使用更安全的身份验证流,例如 Azure 资源的托管标识,或 SQL Server 的 Windows 身份验证。
下面是更改密码的简单示例:
class Program {
   static void Main(string[] args) {
      System.Data.SqlClient.SqlConnection.ChangePassword(
        "Data Source=a_server;Initial Catalog=a_database;UID=user;PWD=old_password",
       "new_password");
   }
}
Module Module1
    Sub Main()
System.Data.SqlClient.SqlConnection.ChangePassword(
        "Data Source=a_server;Initial Catalog=a_database;UID=user;PWD=old_password",
       "new_password")
    End Sub
End Module
以下控制台应用程序演示了更改用户密码所涉及的问题,因为当前密码已过期。
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
    static void Main()
    {
        try
        {
            DemonstrateChangePassword();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
        Console.WriteLine("Press ENTER to continue...");
        Console.ReadLine();
    }
    private static void DemonstrateChangePassword()
    {
        // Retrieve the connection string. In a production application,
        // this string should not be contained within the source code.
        string connectionString = GetConnectionString();
        using (SqlConnection cnn = new SqlConnection())
        {
            for (int i = 0; i <= 1; i++)
            {
                // Run this loop at most two times. If the first attempt fails,
                // the code checks the Number property of the SqlException object.
                // If that contains the special values 18487 or 18488, the code
                // attempts to set the user's password to a new value.
                // Assuming this succeeds, the second pass through
                // successfully opens the connection.
                // If not, the exception handler catches the exception.
                try
                {
                    cnn.ConnectionString = connectionString;
                    cnn.Open();
                    // Once this succeeds, just get out of the loop.
                    // No need to try again if the connection is already open.
                    break;
                }
                catch (SqlException ex)
                {
                    if (i == 0 && ((ex.Number == 18487) || (ex.Number == 18488)))
                    {
                        // You must reset the password.
                        connectionString =
                            ModifyConnectionString(connectionString,
                            GetNewPassword());
                    }
                    else
                    {
                        // Bubble all other SqlException occurrences
                        // back up to the caller.
                        throw;
                    }
                }
            }
            SqlCommand cmd = new SqlCommand(
                "SELECT ProductID, Name FROM Product", cnn);
            // Use the connection and command here...
        }
    }
    private static string ModifyConnectionString(
        string connectionString, string NewPassword)
    {
        // Use the SqlConnectionStringBuilder class to modify the
        // password portion of the connection string.
        SqlConnectionStringBuilder builder =
            new SqlConnectionStringBuilder(connectionString);
        builder.Password = NewPassword;
        return builder.ConnectionString;
    }
    private static string GetNewPassword()
    {
        // In a real application, you might display a modal
        // dialog box to retrieve the new password. The concepts
        // are the same as for this simple console application, however.
        Console.Write("Your password must be reset. Enter a new password: ");
        return Console.ReadLine();
    }
    private static string GetConnectionString()
    {
        // For this demonstration, the connection string must
        // contain both user and password information. In your own
        // application, you might want to retrieve this setting
        // from a config file, or from some other source.
        // In a production application, you would want to
        // display a modal form that could gather user and password
        // information.
        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(
            "Data Source=(local);Initial Catalog=AdventureWorks");
        Console.Write("Enter your user id: ");
        builder.UserID = Console.ReadLine();
        Console.Write("Enter your password: ");
        builder.Password = Console.ReadLine();
        return builder.ConnectionString;
    }
}
Option Explicit On
Option Strict On
Imports System.Data
Imports System.Data.SqlClient
Module Module1
    Sub Main()
        Try
            DemonstrateChangePassword()
        Catch ex As Exception
            Console.WriteLine("Error: " & ex.Message)
        End Try
        Console.WriteLine("Press ENTER to continue...")
        Console.ReadLine()
    End Sub
    Private Sub DemonstrateChangePassword()
        Dim connectionString As String = GetConnectionString()
        Using cnn As New SqlConnection()
            For i As Integer = 0 To 1
                ' Run this loop at most two times. If the first attempt fails, 
                ' the code checks the Number property of the SqlException object.
                ' If that contains the special values 18487 or 18488, the code 
                ' attempts to set the user's password to a new value. 
                ' Assuming this succeeds, the second pass through 
                ' successfully opens the connection.
                ' If not, the exception handler catches the exception.
                Try
                    cnn.ConnectionString = connectionString
                    cnn.Open()
                    ' Once this succeeds, just get out of the loop.
                    ' No need to try again if the connection is already open.
                    Exit For
                Catch ex As SqlException _
                 When (i = 0 And (ex.Number = 18487 Or ex.Number = 18488))
                    ' You must reset the password.
                    connectionString = ModifyConnectionString( _
                     connectionString, GetNewPassword())
                Catch ex As SqlException
                    ' Bubble all other SqlException occurrences
                    ' back up to the caller.
                    Throw
                End Try
            Next
            Dim cmd As New SqlCommand("SELECT ProductID, Name FROM Product", cnn)
            ' Use the connection and command here...
        End Using
    End Sub
    Private Function ModifyConnectionString( _
     ByVal connectionString As String, ByVal NewPassword As String) As String
        ' Use the SqlConnectionStringBuilder class to modify the
        ' password portion of the connection string. 
        Dim builder As New SqlConnectionStringBuilder(connectionString)
        builder.Password = NewPassword
        Return builder.ConnectionString
    End Function
    Private Function GetNewPassword() As String
        ' In a real application, you might display a modal
        ' dialog box to retrieve the new password. The concepts
        ' are the same as for this simple console application, however.
        Console.Write("Your password must be reset. Enter a new password: ")
        Return Console.ReadLine()
    End Function
    Private Function GetConnectionString() As String
        ' For this demonstration, the connection string must
        ' contain both user and password information. In your own
        ' application, you might want to retrieve this setting
        ' from a config file, or from some other source.
        ' In a production application, you would want to 
        ' display a modal form that could gather user and password
        ' information.
        Dim builder As New SqlConnectionStringBuilder( _
         "Data Source=(local);Initial Catalog=AdventureWorks")
        Console.Write("Enter your user id: ")
        builder.UserID = Console.ReadLine()
        Console.Write("Enter your password: ")
        builder.Password = Console.ReadLine()
        Return builder.ConnectionString
    End Function
End Module
注解
在 Windows Server 上使用 SQL Server 时,可以利用允许客户端应用程序同时提供当前密码和新密码的功能来更改现有密码。 应用程序可以在初始登录期间提示用户输入新密码(如果旧密码已过期),并且无需管理员干预即可完成此操作。
警告
Microsoft不建议直接提供用户名和密码,因为它是不安全模式。 如果可能,请使用更安全的身份验证流,例如 Azure 资源的托管标识,或 SQL Server 的 Windows 身份验证。
              ChangePassword 方法将提供的 connectionString 参数中指示的用户的 SQL Server 密码更改为 newPassword 参数中提供的值。 如果连接字符串包含集成安全性的选项(即“Integrated Security=True”或等效项),则会引发异常。
若要确定密码已过期,调用 Open 方法将引发 SqlException。 若要指示必须重置连接字符串中包含的密码,异常的 Number 属性包含状态值 18487 或 18488。 第一个值 (18487) 指示密码已过期,第二个值 (18488) 指示在登录之前必须重置密码。
此方法打开与服务器自身的连接,请求密码更改,并在连接完成后立即关闭连接。 不会从 SQL Server 连接池中检索或返回此连接。
另请参阅
- 连接字符串 (ADO.NET)
- 连接到数据源(ADO.NET)
- 使用适用于 SQL Server 的 .NET Framework 数据提供程序 
- ADO.NET 概述