SqlConnection.ChangePassword メソッドとは? わかりやすく解説

Weblio 辞書 > コンピュータ > .NET Framework クラス ライブラリ リファレンス > SqlConnection.ChangePassword メソッドの意味・解説 

SqlConnection.ChangePassword メソッド

メモ : このメソッドは、.NET Framework version 2.0 で新しく追加されたものです。

接続文字列中に指定されているユーザーの SQL Server パスワードを、指定された新しいパスワードに変更します。

名前空間: System.Data.SqlClient
アセンブリ: System.Data (system.data.dll 内)
構文構文

Public Shared Sub ChangePassword
 ( _
    connectionString As String, _
    newPassword As String _
)
Dim connectionString As String
Dim newPassword As String

SqlConnection.ChangePassword(connectionString, newPassword)
public static void ChangePassword
 (
    string connectionString,
    string newPassword
)
public:
static void ChangePassword (
    String^ connectionString, 
    String^ newPassword
)
public static void ChangePassword
 (
    String connectionString, 
    String newPassword
)
public static function ChangePassword
 (
    connectionString : String, 
    newPassword : String
)

パラメータ

connectionString

目的のサーバーに接続するために必要な情報を保持する接続文字列。接続文字列には、ユーザー ID および現在のパスワードが含まれている必要があります。

newPassword

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

例外例外
例外の種類条件

ArgumentException

接続文字列に、統合セキュリティを使用するためのオプションが含まれます。

ArgumentNullException

connectionString パラメータまたは newPassword パラメータが null です。

解説解説

Windows Server 2003 以降で SQL Server 2005 を使用している場合、現在のパスワードと新しいパスワードの両方を指定して既存のパスワードを変更できるようにする機能をクライアント アプリケーションに実装できます。たとえば、最初のログイン時に、古いパスワードの期限が切れていた場合、管理者が介入することなく、ユーザーに新しいパスワードの入力を求めることもできます。

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

パスワードの有効期限が切れているかどうかは、Open メソッドを使用し、SqlException を発生させることによって判断できます。接続文字列中のパスワードをリセットする必要がある場合は、Number プロパティに 18487 または 18488 のステータス値が格納されます。ここで、18487 はパスワードの有効期限が切れていることを示し、18488 はパスワードをリセットしてからログインする必要があることを示します。

このメソッドでは、サーバーに対する専用の接続を確立し、パスワードの変更を要求して、変更が完了した段階で接続が解除されます。この接続が SQL Server の接続プールから取得されたり、逆に接続プールに戻されたりすることはありません。

使用例使用例

次のコンソール アプリケーションでは、現在のパスワードの有効期限が切れている場合に、ユーザーにパスワードの変更を求めます。

Option Explicit On
Option Strict On

Imports System
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
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;
    }
}
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照



英和和英テキスト翻訳

英語⇒日本語日本語⇒英語

辞書ショートカット

すべての辞書の索引

SqlConnection.ChangePassword メソッドのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



SqlConnection.ChangePassword メソッドのページの著作権

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2026 Microsoft.All rights reserved.

©2026 GRAS Group, Inc.RSS