SqlConnection.ChangePassword SqlConnection.ChangePassword SqlConnection.ChangePassword SqlConnection.ChangePassword Method

Определение

Изменяет пароль SQL Server.Changes the SQL Server password.

Перегрузки

ChangePassword(String, String) ChangePassword(String, String) ChangePassword(String, String) ChangePassword(String, String)

Заменяет пароль SQL Server для пользователя, указанного в строке подключения, заданным новым паролем.Changes the SQL Server password for the user indicated in the connection string to the supplied new password.

ChangePassword(String, SqlCredential, SecureString) ChangePassword(String, SqlCredential, SecureString) ChangePassword(String, SqlCredential, SecureString) ChangePassword(String, SqlCredential, SecureString)

Изменяет пароль SQL Server для пользователя, указанного в объекте SqlCredential.Changes the SQL Server password for the user indicated in the SqlCredential object.

ChangePassword(String, String) ChangePassword(String, String) ChangePassword(String, String) ChangePassword(String, String)

Заменяет пароль SQL Server для пользователя, указанного в строке подключения, заданным новым паролем.Changes the SQL Server password for the user indicated in the connection string to the supplied new password.

public:
 static void ChangePassword(System::String ^ connectionString, System::String ^ newPassword);
public static void ChangePassword (string connectionString, string newPassword);
static member ChangePassword : string * string -> unit
Public Shared Sub ChangePassword (connectionString As String, newPassword As String)

Параметры

connectionString
String String String String

Строка подключения, содержащая достаточно информации для подключения к требуемому серверу.The connection string that contains enough information to connect to the server that you want. В строке подключения должны быть заданы идентификатор пользователя и его текущий пароль.The connection string must contain the user ID and the current password.

newPassword
String String String String

Новый пароль.The new password to set. Новый пароль должен соответствовать установленной на сервере политике безопасности паролей, включая минимальную длину, требования к использованию определенных знаков и т. д.This password must comply with any password security policy set on the server, including minimum length, requirements for specific characters, and so on.

Исключения

Строка подключения содержит параметр, позволяющий использовать встроенную систему безопасности.The connection string includes the option to use integrated security.

ИлиOr Длина параметра newPassword превышает 128 символов.The newPassword exceeds 128 characters.

Либо параметр connectionString, либо newPassword имеет значение NULL.Either the connectionString or the newPassword parameter is null.

Примеры

Ниже приведен простой пример изменения пароля.The following is a simple example of changing a password:

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  
  

В следующем консольном приложении показаны проблемы, связанные с изменением пароля пользователя, так как истек срок действия текущего пароля.The following console application demonstrates the issues involved in changing a user's password because the current password has expired.

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

Комментарии

При использовании SQL Server в Windows Server разработчики могут воспользоваться преимуществами функций, позволяющих клиентскому приложению указать текущий и новый пароль для изменения существующего пароля.When you are using SQL Server on Windows Server, developers can take advantage of functionality that lets the client application supply both the current and a new password in order to change the existing password. Приложения могут реализовывать такие функции, как запрос нового пароля при первом входе в систему, если срок действия старого имени входа истек, и эта операция может завершиться без вмешательства администратора.Applications can implement functionality such as prompting the user for a new password during initial login if the old one has expired, and this operation can be completed without administrator intervention.

Метод изменяет SQL Server пароль пользователя, указанного в указанном connectionString параметре, на значение, указанное в newPassword параметре. ChangePasswordThe ChangePassword method changes the SQL Server password for the user indicated in the supplied connectionString parameter to the value supplied in the newPassword parameter. Если строка подключения включает параметр для встроенной безопасности (то есть "Integrated Security = true" или эквивалентный), создается исключение.If the connection string includes the option for integrated security (that is, "Integrated Security=True" or the equivalent), an exception is thrown.

Чтобы определить, что срок действия пароля истек, вызов Open метода SqlExceptionвызывает метод.To determine that the password has expired, calling the Open method raises a SqlException. Чтобы указать, что пароль, содержащийся в строке подключения, должен быть сброшен, Number свойство для исключения содержит значение состояния 18487 или 18488.In order to indicate that the password that is contained within the connection string must be reset, the Number property for the exception contains the status value 18487 or 18488. Первое значение (18487) указывает, что срок действия пароля истек, а второй (18488) указывает, что пароль необходимо сбросить перед входом в систему.The first value (18487) indicates that the password has expired and the second (18488) indicates that the password must be reset before logging in.

Этот метод открывает собственное подключение к серверу, запрашивает изменение пароля и закрывает соединение сразу после его завершения.This method opens its own connection to the server, requests the password change, and closes the connection as soon as it has completed. Это соединение не извлекается из пула подключений SQL Server и не возвращается в него.This connection is not retrieved from, nor returned to, the SQL Server connection pool.

Дополнительно

ChangePassword(String, SqlCredential, SecureString) ChangePassword(String, SqlCredential, SecureString) ChangePassword(String, SqlCredential, SecureString) ChangePassword(String, SqlCredential, SecureString)

Изменяет пароль SQL Server для пользователя, указанного в объекте SqlCredential.Changes the SQL Server password for the user indicated in the SqlCredential object.

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 newSecurePassword);
static member ChangePassword : string * System.Data.SqlClient.SqlCredential * System.Security.SecureString -> unit
Public Shared Sub ChangePassword (connectionString As String, credential As SqlCredential, newSecurePassword As SecureString)

Параметры

connectionString
String String String String

Строка подключения, содержащая достаточно информации для подключения к серверу.The connection string that contains enough information to connect to a server. Строка подключения не должна использовать любое из следующих ключевых слов строки подключения: Integrated Security = true, UserId, Password или ContextConnection = true.The connection string should not use any of the following connection string keywords: Integrated Security = true, UserId, or Password; or ContextConnection = true.

newPassword
SecureString SecureString SecureString SecureString

Новый пароль.newPasswordThe new password.newPassword должен быть доступен только для чтения.must be read only. Пароль должен также соответствовать установленной на сервере политике безопасности паролей, (например, минимальной длине и требованиям к использованию определенных символов).The password must also comply with any password security policy set on the server (for example, minimum length and requirements for specific characters).

Исключения

Строка подключения содержит любое сочетание UserId, Password и Integrated Security=true.The connection string contains any combination of UserId, Password, or Integrated Security=true.

- или --or- Строка подключения содержит Context Connection=true.The connection string contains Context Connection=true.

- или --or-

Длина newSecurePassword (или newPassword) больше 128 символов.newSecurePassword (or newPassword) is greater than 128 characters.

-или--or-

newSecurePassword (или newPassword) доступен не только для чтения.newSecurePassword (or newPassword) is not read only.

- или --or-

newSecurePassword (или newPassword) является пустой строкой.newSecurePassword (or newPassword) is an empty string.

Один из параметров (connectionString, credential или newSecurePassword) имеет значение NULL.One of the parameters (connectionString, credential, or newSecurePassword) is null.

Дополнительно

Применяется к