SqlConnection.ChangePassword Metoda

Definice

Změní heslo SQL Server.

Přetížení

ChangePassword(String, String)

Změní heslo SQL Server uživatele uvedeného v připojovací řetězec na zadané nové heslo.

ChangePassword(String, SqlCredential, SecureString)

Změní heslo SQL Server uživatele uvedeného v objektu SqlCredential .

ChangePassword(String, String)

Změní heslo SQL Server uživatele uvedeného v připojovací řetězec na zadané nové heslo.

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)

Parametry

connectionString
String

Připojovací řetězec obsahující dostatek informací pro připojení k požadovanému serveru. připojovací řetězec musí obsahovat ID uživatele a aktuální heslo.

newPassword
String

Nové heslo, které se má nastavit. Toto heslo musí splňovat všechny zásady zabezpečení hesel nastavené na serveru, včetně minimální délky, požadavků na určité znaky atd.

Výjimky

Připojovací řetězec zahrnuje možnost použít integrované zabezpečení.

Nebo

Hodnota newPassword přesahuje 128 znaků.

connectionString Parametr nebo newPassword má hodnotu null.

Příklady

Následuje jednoduchý příklad změny hesla:

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

Následující konzolová aplikace ukazuje problémy spojené se změnou hesla uživatele, protože vypršela platnost aktuálního hesla.

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

Poznámky

Pokud používáte SQL Server ve Windows Serveru, můžou vývojáři využít funkce, které klientské aplikaci umožňují zadat aktuální i nové heslo, aby mohli změnit stávající heslo. Aplikace můžou implementovat funkce, jako je například výzva k zadání nového hesla při počátečním přihlášení, pokud vypršela platnost starého hesla, a tuto operaci je možné dokončit bez zásahu správce.

Metoda ChangePassword změní SQL Server heslo uživatele uvedeného v zadaném connectionString parametru na hodnotu zadanou v parametru newPassword . Pokud připojovací řetězec obsahuje možnost integrovaného zabezpečení (tj. Integrované zabezpečení = Pravda nebo ekvivalentní), vyvolá se výjimka.

Pokud chcete zjistit, že vypršela platnost hesla, vyvolá volání Open metody SqlException. Aby bylo možné označit, že heslo obsažené v připojovací řetězec musí být resetováno, Number obsahuje vlastnost výjimky hodnotu stavu 18487 nebo 18488. První hodnota (18487) označuje, že platnost hesla vypršela, a druhá (18488) znamená, že před přihlášením je potřeba heslo resetovat.

Tato metoda otevře vlastní připojení k serveru, požádá o změnu hesla a ukončí připojení, jakmile se dokončí. Toto připojení se nenačte ani nevrátí do fondu připojení SQL Server.

Viz také

Platí pro

ChangePassword(String, SqlCredential, SecureString)

Změní heslo SQL Server uživatele uvedeného v objektu SqlCredential .

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)

Parametry

connectionString
String

Připojovací řetězec obsahující dostatek informací pro připojení k serveru. Připojovací řetězec by neměla používat žádná z následujících připojovací řetězec klíčových slov: Integrated Security = true, UserIdnebo Password; nebo ContextConnection = true.

credential
SqlCredential

Objekt SqlCredential .

newPasswordnewSecurePassword
SecureString

Nové heslo.newPassword musí být jen pro čtení. Heslo musí také splňovat všechny zásady zabezpečení hesel nastavené na serveru (například minimální délka a požadavky na určité znaky).

Výjimky

Připojovací řetězec obsahuje libovolnou kombinaci , UserIdPasswordnebo Integrated Security=true.

-nebo-

Připojovací řetězec obsahuje Context Connection=true.

-nebo-

newSecurePassword (nebo newPassword) je větší než 128 znaků.

-nebo-

newSecurePassword (nebo newPassword) není jen pro čtení.

-nebo-

newSecurePassword (nebo newPassword) je prázdný řetězec.

Jeden z parametrů (connectionString, credentialnebo newSecurePassword) má hodnotu null.

Viz také

Platí pro