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

注釈

Windows Server でSQL Serverを使用している場合、開発者は、クライアント アプリケーションが現在のパスワードと新しいパスワードの両方を指定して既存のパスワードを変更できるようにする機能を利用できます。 アプリケーションは、古いパスワードの有効期限が切れている場合に、初期ログイン時にユーザーに新しいパスワードの入力を求めるなどの機能を実装でき、管理者の介入なしにこの操作を完了できます。

メソッドはChangePassword、指定されたconnectionStringパラメーターで示されているユーザーのSQL Serverパスワードを、 パラメーターで指定された値にnewPassword変更します。 接続文字列に統合セキュリティのオプション ("Integrated Security=True" またはそれに相当するもの) が含まれている場合は、例外がスローされます。

パスワードの有効期限が切れたことを確認するには、 メソッドを Open 呼び出すと、 SqlExceptionが発生します。 接続文字列に含まれるパスワードをリセットする必要があることを示すために、例外の Number プロパティには状態値 18487 または 18488 が含まれます。 最初の値 (18487) はパスワードの有効期限が切れたことを示し、2 番目の値 (18488) はログイン前にパスワードをリセットする必要があることを示します。

このメソッドは、サーバーへの独自の接続を開き、パスワードの変更を要求し、接続が完了するとすぐに接続を閉じます。 この接続は、SQL Server接続プールから取得されたり、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 = trueUserIdPasswordContextConnection = true のいずれの接続文字列のキーワードも使用すべきではありません。

credential
SqlCredential

SqlCredential オブジェクト。

newPasswordnewSecurePassword
SecureString

新しいパスワード。newPassword は読み取り専用でなければなりません。 このパスワードは、サーバー側で設定されているパスワード セキュリティ ポリシー (最低限の長さ、使用文字の要件など) も満たしている必要があります。

例外

接続の文字列には UserIdPassword、または Integrated Security=true の組み合わせのいずれかが含まれています。

- または -

Context Connection=true を含む接続文字列。

- または -

newSecurePassword (または newPassword) が 128 文字を超えています。

- または -

newSecurePassword (または newPassword) は読み取り専用ではありません。

- または -

newSecurePassword (または newPassword) が空の文字列です。

パラメーターのうちの 1 つ (connectionStringcredential、または newSecurePassword) が null です。

こちらもご覧ください

適用対象