Language

DbProviderFactory を取得する

DbProviderFactory を取得する過程では、データ プロバイダーに関する情報が DbProviderFactories クラスに渡されます。 この情報に基づいて、 GetFactory メソッドは厳密に型指定されたプロバイダー ファクトリを返します。 たとえば、SqlClientFactory を登録した後、GetFactory にプロバイダー名 Microsoft.Data.SqlClient を渡します。 GetFactoryのもう 1 つのオーバーロードは、DataRowを受け取ります。 プロバイダー ファクトリを取得したら、そのメソッドを使用して追加のオブジェクトを作成できます。 SqlClientFactory のメソッドには、CreateConnection、CreateCommand、CreateDataAdapter などがあります。

注

同様の機能は、OracleClientFactory クラス、OdbcFactory クラス、および OleDbFactory クラスにも用意されています。

DbProviderFactory の登録

Microsoft.Data.SqlClient NuGet パッケージをファクトリを登録する前にインストールします。

.NET Framework で、アプリケーションのconfigurationまたはsystem.dataファイルのweb.config要素内に、次のapp.configセクションを追加します。 remove要素は、別の構成ファイルから継承された重複登録を防止します。

<system.data>
  <DbProviderFactories>
    <remove invariant="Microsoft.Data.SqlClient" />
    <add name="Microsoft SqlClient Data Provider"
     invariant="Microsoft.Data.SqlClient"
     description="Microsoft SqlClient Data Provider for SQL Server"
     type="Microsoft.Data.SqlClient.SqlClientFactory, Microsoft.Data.SqlClient"
    />
  </DbProviderFactories>
</system.data>

最新の.NETでは、構成ファイルではプロバイダー ファクトリは登録されません。 GetFactoryを呼び出す前に、プロバイダー名としてRegisterFactory(String, DbProviderFactory)を使用してMicrosoft.Data.SqlClientを呼び出し、ファクトリ インスタンスとしてInstanceを指定してください。 RegisterFactoryは、.NET Framework では使用できません。

次の例では、モダン .NET 向けのコードでファクトリを登録します。 .NET Framework の場合は、前の構成エントリを使用し、RegisterFactory呼び出しを省略します。

インバリアント プロバイダー名は、基になるデータ プロバイダーを識別します。 ファクトリ参照と接続文字列のproviderName属性に同じ名前を使用します。

プロバイダー情報の取得

GetFactoryClasses メソッドを使用して、登録済みデータ プロバイダーに関する情報を取得できます。 次の表に示す列を含むDataTableという名前のDbProviderFactoriesを返します。 この例の値は、前に示した .NET Framework 構成エントリに対応しています。アセンブリのバージョンの詳細は、インストールされているパッケージによって異なります。

列の序数 列名 サンプルの出力 説明
0 Name Microsoft SqlClient Data Provider データプロバイダーのわかりやすい名前
1 Description Microsoft SqlClient Data Provider for SQL Server データ プロバイダーの読み取り可能な説明
2 InvariantName Microsoft.Data.SqlClient プログラムでデータ プロバイダーの参照に使用できる名前
3 AssemblyQualifiedName Microsoft.Data.SqlClient.SqlClientFactory, Microsoft.Data.SqlClient ファクトリ クラスのアセンブリ修飾名

この DataTable は、実行時にユーザーが DataRow を選択できるようにするために使用できます。 次に、選択された DataRow を GetFactory メソッドに渡すことで、厳密に型指定された DbProviderFactory を作成できます。 選択された DataRow を GetFactory メソッドに渡すことによって、目的の DbProviderFactory オブジェクトを作成できます。

インストールされているプロバイダー ファクトリ クラスの一覧表示

次の例では、インストールされているプロバイダーの情報を含んだ GetFactoryClasses を、DataTable メソッドを使用して取得します。 このコードは、DataTable 内の各行を反復処理しながら、インストールされている各プロバイダーの情報をコンソール ウィンドウに表示します。

    // This example assumes a reference to System.Data.Common.
    static DataTable GetProviderFactoryClasses()
    {
#if !NETFRAMEWORK
        DbProviderFactories.RegisterFactory("Microsoft.Data.SqlClient", SqlClientFactory.Instance);
#endif

        // Retrieve the installed providers and factories.
        DataTable table = DbProviderFactories.GetFactoryClasses();

        // Display each row and column value.
        foreach (DataRow row in table.Rows)
        {
            foreach (DataColumn column in table.Columns)
            {
                Console.WriteLine(row[column]);
            }
        }
        return table;
    }
    ' This example assumes a reference to System.Data.Common.
    Private Shared Function GetProviderFactoryClasses() As DataTable

#If Not NETFRAMEWORK Then
        DbProviderFactories.RegisterFactory("Microsoft.Data.SqlClient", SqlClientFactory.Instance)
#End If

        ' Retrieve the installed providers and factories.
        Dim table As DataTable = DbProviderFactories.GetFactoryClasses()

        ' Display each row and column value.
        Dim row As DataRow
        Dim column As DataColumn
        For Each row In table.Rows
            For Each column In table.Columns
                Console.WriteLine(row(column))
            Next
        Next

        Return table
    End Function

アプリケーション構成ファイルを使用したファクトリ情報の保存

ファクトリを使用したデザイン パターンでは、プロバイダーや接続文字列の情報をアプリケーション構成ファイルに保存する必要があります。たとえば、Windows アプリケーションの場合は app.config に、ASP.NET アプリケーションの場合は web.config に、これらの情報を保存することになります。

次の構成ファイル フラグメントは、2 つの名前付き接続文字列 (SQL Server の Northwind データベースに接続するための「NorthwindSQL」と、Access/Jet の Northwind データベースに接続するための「NorthwindAccess」) を保存する例を示したものです。 invariant名は、providerName属性に使用されます。

<configuration>
  <connectionStrings>
    <clear/>
    <add name="NorthwindSQL"
     providerName="Microsoft.Data.SqlClient"
     connectionString=
     "Data Source=&lt;server&gt;;Initial Catalog=Northwind;Integrated Security=true;Encrypt=true"
    />

    <add name="NorthwindAccess"
     providerName="System.Data.OleDb"
     connectionString=
     "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Northwind.mdb;"
    />
  </connectionStrings>
</configuration>

重要

Microsoft では、使用可能な最も安全な認証フローを使用することをお勧めします。 Azure SQL に接続する場合は、Azure リソースの管理 ID が推奨される認証方法です。

接続文字列をプロバイダー名で取得する

プロバイダー ファクトリ経由で接続を作成するには、接続文字列とプロバイダー名を指定します。 この例では、Microsoft.Data.SqlClientなどの不変プロバイダー名を渡して、アプリケーション構成ファイルから接続文字列を取得する方法を示します。 このコードでは、ConnectionStringSettingsCollection を反復処理しています。 成功した場合は一致する接続文字列が返されます。それ以外の場合はnull が返されます (Visual BasicでNothing)。 プロバイダーに複数のエントリが存在した場合は、最初に見つかったエントリが返されます。 構成ファイルからの接続文字列の取得およびその例については、「接続文字列と構成ファイル」を参照してください。

注

このコードを実行するには、System.Configuration.dll を参照設定する必要があります。

// Retrieve a connection string by specifying the providerName.
// Assumes one connection string per provider in the config file.
static string? GetConnectionStringByProvider(string providerName)
{
    // Get the collection of connection strings.
    ConnectionStringSettingsCollection? settings =
        ConfigurationManager.ConnectionStrings;

    // Walk through the collection and return the first
    // connection string matching the providerName.
    if (settings != null)
    {
        foreach (ConnectionStringSettings cs in settings)
        {
            if (cs.ProviderName == providerName)
            {
                return cs.ConnectionString;
            }
        }
    }
    return null;
}
' Retrieve a connection string by specifying the providerName.
' Assumes one connection string per provider in the config file.
Private Shared Function GetConnectionStringByProvider( _
    ByVal providerName As String) As String

    'Return Nothing on failure.
    Dim returnValue As String = Nothing

    ' Get the collection of connection strings.
    Dim settings As ConnectionStringSettingsCollection = _
        ConfigurationManager.ConnectionStrings

    ' Walk through the collection and return the first 
    ' connection string matching the providerName.
    If Not settings Is Nothing Then
        For Each cs As ConnectionStringSettings In settings
            If cs.ProviderName = providerName Then
                returnValue = cs.ConnectionString
                Exit For
            End If
        Next
    End If

    Return returnValue
End Function

DbProviderFactory および DbConnection の作成

この例では、DbConnection などの不変プロバイダー名と接続文字列を渡して、Microsoft.Data.SqlClientオブジェクトとDbProviderFactoryオブジェクトを作成する方法を示します。 成功した場合には DbConnection オブジェクトが返されます。エラーが発生した場合は null (Visual Basic の場合は Nothing) が返されます。

このコードでは、DbProviderFactory を呼び出すことによって GetFactory を取得しています。 次に、CreateConnection メソッドで DbConnection オブジェクトを作成し、ConnectionString プロパティに接続文字列を設定します。

    // Given a provider name and connection string,
    // create the DbProviderFactory and DbConnection.
    // Returns a DbConnection on success; null on failure.
    static DbConnection CreateDbConnection(
        string providerName, string connectionString)
    {
        // Assume failure.
        DbConnection connection = null;

        // Create the DbProviderFactory and DbConnection.
        if (connectionString != null)
        {
            try
            {
#if !NETFRAMEWORK
                if (providerName == "Microsoft.Data.SqlClient")
                {
                    DbProviderFactories.RegisterFactory(providerName, SqlClientFactory.Instance);
                }
#endif

                DbProviderFactory factory =
                    DbProviderFactories.GetFactory(providerName);

                connection = factory.CreateConnection();
                connection.ConnectionString = connectionString;
            }
            catch (Exception ex)
            {
                // Set the connection to null if it was created.
                if (connection != null)
                {
                    connection = null;
                }
                Console.WriteLine(ex.Message);
            }
        }
        // Return the connection.
        return connection;
    }
    ' Given a provider, create a DbProviderFactory and DbConnection.
    ' Returns a DbConnection on success; Nothing on failure.
    Private Shared Function CreateDbConnection( _
        ByVal providerName As String, ByVal connectionString As String) _
        As DbConnection

        ' Assume failure.
        Dim connection As DbConnection = Nothing

        ' Create the DbProviderFactory and DbConnection.
        If Not connectionString Is Nothing Then
            Try
#If Not NETFRAMEWORK Then
                DbProviderFactories.RegisterFactory("Microsoft.Data.SqlClient", SqlClientFactory.Instance)
#End If
                Dim factory As DbProviderFactory = _
                   DbProviderFactories.GetFactory(providerName)

                connection = factory.CreateConnection()
                connection.ConnectionString = connectionString

            Catch ex As Exception
                ' Set the connection to Nothing if it was created.
                If Not connection Is Nothing Then
                    connection = Nothing
                End If
                Console.WriteLine(ex.Message)
            End Try
        End If

        ' Return the connection.
        Return connection
    End Function

関連項目