SqlConnection.ChangePassword 메서드

정의

SQL Server 암호를 변경합니다.

오버로드

ChangePassword(String, String)

연결 문자열에 지정된 사용자의 SQL Server 암호를 제공된 새 암호로 변경합니다.

ChangePassword(String, SqlCredential, SecureString)

SqlCredential 개체에 지정된 사용자에 대한 SQL Server 암호를 변경합니다.

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 -> unit
Public Shared Sub ChangePassword (connectionString As String, newPassword As String)

매개 변수

connectionString
String

원하는 서버에 연결하는 데 충분한 정보가 포함된 연결 문자열입니다. 연결 문자열은 사용자 ID와 현재 암호를 포함해야 합니다.

newPassword
String

설정할 새 암호입니다. 이 암호는 서버에 설정된 최소 길이, 특정 문자 요구 사항 등의 암호 보안 정책을 따라야 합니다.

예외

연결 문자열에 통합 보안을 사용할 수 있는 옵션이 포함된 경우

Or

newPassword가 128자를 초과합니다.

connectionString 또는 newPassword 매개 변수가 null인 경우

예제

다음은 암호를 변경하는 간단한 예입니다.

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

설명

SQL Server를 Windows Server에서 사용 하는 경우 개발자가 기존 암호를 변경 하려면 현재 및 새 암호를 제공 하는 클라이언트 애플리케이션을 수 있는 기능을 활용을 걸릴 수 있습니다. 애플리케이션은 이전 암호가 만료된 경우 초기 로그인 중에 사용자에게 새 암호를 묻는 메시지를 표시하는 등의 기능을 구현할 수 있으며 관리자의 개입 없이 이 작업을 완료할 수 있습니다.

메서드는 ChangePassword 제공된 connectionString 매개 변수에 표시된 사용자의 SQL Server 암호를 매개 변수에 newPassword 제공된 값으로 변경합니다. 연결 문자열 통합 보안 옵션(즉, "통합 보안=True" 또는 이에 해당)이 포함된 경우 예외가 throw됩니다.

암호가 만료되었는지 확인하려면 메서드를 호출하면 Open 가 발생합니다 SqlException. 연결 문자열 포함된 암호를 다시 Number 설정해야 함을 나타내기 위해 예외의 속성에는 상태 값 18487 또는 18488이 포함됩니다. 첫 번째 값(18487)은 암호가 만료되었음을 나타내고 두 번째 값(18488)은 로그인하기 전에 암호를 재설정해야 했음을 나타냅니다.

이 메서드는 서버에 대한 자체 연결을 열고, 암호 변경을 요청하고, 완료되는 즉시 연결을 닫습니다. 이 연결은 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 -> unit
static member ChangePassword : string * System.Data.SqlClient.SqlCredential * System.Security.SecureString -> unit
Public 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입니다.

추가 정보

적용 대상