SqlConnection.ChangePassword Methode

Definition

Ändert das SQL Server-Kennwort.

Überlädt

ChangePassword(String, String)

Ändert das SQL Server-Kennwort für den Benutzer, der in der Verbindungszeichenfolge zum bereitgestellten neuen Kennwort angegeben ist.

ChangePassword(String, SqlCredential, SecureString)

Ändert das SQL Server-Kennwort für den Benutzer, der im SqlCredential-Objekt angegeben wird.

ChangePassword(String, String)

Ändert das SQL Server-Kennwort für den Benutzer, der in der Verbindungszeichenfolge zum bereitgestellten neuen Kennwort angegeben ist.

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)

Parameter

connectionString
String

Verbindungszeichenfolge mit den notwendigen Informationen, um eine Verbindung mit dem gewünschten Server herzustellen. Die Verbindungszeichenfolge muss die Benutzer-ID und das aktuelle Kennwort enthalten.

newPassword
String

Das neue anzugebende Kennwort. Das Kennwort muss allen auf dem Server festgelegten Sicherheitsrichtlinien für Kennwörter entsprechen, einschließlich der Mindestlänge, erforderlicher Sonderzeichen usw.

Ausnahmen

Die Verbindungszeichenfolge enthält die Option, integrierte Sicherheit zu verwenden.

Or

Das newPassword ist länger als 128 Zeichen.

Entweder der connectionString- oder der newPassword-Parameter ist gleich NULL.

Beispiele

Es folgt ein einfaches Beispiel für das Ändern eines Kennworts:

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

Die folgende Konsolenanwendung veranschaulicht die Probleme beim Ändern des Kennworts eines Benutzers, da das aktuelle Kennwort abgelaufen ist.

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

Hinweise

Wenn Sie SQL Server unter Windows Server verwenden, können Entwickler die Funktionen nutzen, mit denen die Clientanwendung sowohl das aktuelle als auch ein neues Kennwort angeben kann, um das vorhandene Kennwort zu ändern. Anwendungen können Funktionen implementieren, z. B. die Aufforderung zum Eingeben eines neuen Kennworts bei der ersten Anmeldung, wenn das alte abgelaufen ist, und dieser Vorgang kann ohne Administratoreingriff abgeschlossen werden.

Die ChangePassword -Methode ändert das SQL Server Kennwort für den im angegebenen connectionString Parameter angegebenen Benutzer in den im newPassword Parameter angegebenen Wert. Wenn die Verbindungszeichenfolge die Option für integrierte Sicherheit enthält (d. h. "Integrated Security=True" oder die entsprechende), wird eine Ausnahme ausgelöst.

Um festzustellen, ob das Kennwort abgelaufen ist, löst das Aufrufen der Open -Methode einen aus SqlException. Um anzugeben, dass das In der Verbindungszeichenfolge enthaltene Kennwort zurückgesetzt werden muss, enthält die Number -Eigenschaft für die Ausnahme den status Wert 18487 oder 18488. Der erste Wert (18487) gibt an, dass das Kennwort abgelaufen ist, und der zweite Wert (18488) gibt an, dass das Kennwort vor der Anmeldung zurückgesetzt werden muss.

Diese Methode öffnet eine eigene Verbindung mit dem Server, fordert die Kennwortänderung an und schließt die Verbindung, sobald sie abgeschlossen ist. Diese Verbindung wird vom SQL Server Verbindungspool weder abgerufen noch zurückgegeben.

Weitere Informationen

Gilt für:

ChangePassword(String, SqlCredential, SecureString)

Ändert das SQL Server-Kennwort für den Benutzer, der im SqlCredential-Objekt angegeben wird.

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)

Parameter

connectionString
String

Verbindungszeichenfolge mit den notwendigen Informationen, um eine Verbindung mit dem Server herzustellen. Die Verbindungszeichenfolge darf keines der folgenden Schlüsselwörter für Verbindungszeichenfolgen enthalten: Integrated Security = true, UserId oder Password oder ContextConnection = true.

credential
SqlCredential

Ein SqlCredential-Objekt.

newPasswordnewSecurePassword
SecureString

Das neue Kennwort.newPassword muss schreibgeschützt sein. Das Kennwort muss auch allen auf dem Server festgelegten Sicherheitsrichtlinien für Kennwörter entsprechen, (zum Beispiel der Mindestlänge und erforderlicher Sonderzeichen).

Ausnahmen

Die Verbindungszeichenfolge enthält jede Kombination von UserId, Password oder Integrated Security=true.

- oder -

Die Verbindungszeichenfolge enthält Context Connection=true.

- oder -

newSecurePassword (oder newPassword) ist länger als 128 Zeichen.

- oder -

newSecurePassword (oder newPassword) ist nicht schreibgeschützt.

- oder -

newSecurePassword (oder newPassword) ist eine leere Zeichenfolge.

Einer der Parameter (connectionString, credential oder newSecurePassword) ist null.

Weitere Informationen

Gilt für: