本ページでは、ADO.NET Data Provider for POLARDB (POLARDB .NET) ドライバーを使用して、C# アプリケーションを ApsaraDB for POLARDB データベースに接続する方法について説明します。

始める前に

  • ApsaraDB for POLARDB クラスターのアカウントが作成されている必要があります。 アカウントの作成方法の詳細については、「データベースアカウントの作成」をご参照ください。
  • ApsaraDB for POLARDB クラスターに接続するホストの IP アドレスをホワイトリストに追加されている必要があります。 詳細については、「POLARDB クラスターのホワイトリストの設定」をご参照ください。

このタスクについて

POLARDB .NET は、C#、Visual Basic、F#などのプログラミング言語を使用して ApsaraDB for POLARDB に接続するために使用されるドライバーです。 このドライバーは、Entity Framework Core および Entity Framework 6.x と互換性があります。このドライバーを Entity Framework と共に使用すると、アプリケーションをすばやく開発できます。

現在のドライバーは PostgreSQL 3.0 プロトコルを使用しており、.NETFramework 4.x および .NET Core 2.x と互換性があります。

Entity Framework 概要

Entity Framework は、.NET プラットフォームで人気のあるオブジェクトリレーショナルマッパー (O/RM) です。 C# 言語が使用されている場合、言語統合クエリ(LINQ)テクノロジと連携して、バックエンドアプリケーションの開発を大幅に加速します。

POLARDB .NETドライバーは、Entity Framework を使用するときに役立つ POLARDB Entity Framework 5 および 6 dll を提供します。

Entity Framework の詳細については、公式ウェブサイト『https://docs.microsoft.com/en-au/ef/』をご参照ください。

POLARDB .NET ドライバーのダウンロード

POLARDB .NET ドライバーをダウンロード します。

POLARDB .NET ドライバーのインストール

  1. POLARDB .NET ドライバーを解凍します。
    unzip POLARDB-for-Oracle-.net_installer.zip
  2. ドライバーを Visual Studio プロジェクトにインポートします。

    サンプルの <Project> ノードに次のコンテンツを追加します。 csproj または Visual Studio の GUI です。

    <Project>
      ...
      <ItemGroup>
        <Reference Include="POLARDB.POLARDBClient, Version=4.0.4.1, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7">
          <HintPath>${your path}\POLARDB.POLARDBClient.dll</HintPath>
        </Reference>
      </ItemGroup>
      ...
    </Project>

Samples フォルダーで、polardb-sample.sql ファイルと複数のサンプルプロジェクトファイルを確認できます。 次の手順は、これらのサンプルプロジェクトを実行する方法を示しています。

  1. データベースに接続します。 詳細については、「Oracle と互換性のある POLARDB クラスターへの接続」をご参照ください。
  2. 次のコマンドを実行して、sampledb という名前のプロジェクトを作成します。
    CREATE DATABASE sampledb;
  3. テストに必要なデータベース、テーブル、データ、および関数をデータベース sampledb にインポートします。
    \i ${your path}/polardb-sample.sql
  4. データがインポートされたら、C# コードを記述します。

    次のサンプルコードは、ストアドプロシージャを照会、更新、および呼び出す方法を示しています。

    using System;
    using System.Data;
    using POLARDB.POLARDBClient;
    /*
     * This class provides a simple way to perform DML operation in POLARDB
     *
     * @revision 1.0
     */
    
    namespace POLARDBClientTest
    {
    
        class SAMPLE_TEST
        {
    
            static void Main(string[] args)
            {
                POLARDBConnection conn = new POLARDBConnection("Server=localhost;Port=1521;User Id=polaruser;Password=password;Database=sampledb");
                try
                {
                    conn.Open();
    
                    //Simple select statement using POLARDBCommand object
                    POLARDBCommand POLARDBSeletCommand = new POLARDBCommand("SELECT EMPNO,ENAME,JOB,MGR,HIREDATE FROM EMP",conn);
                    POLARDBDataReader SelectResult =  POLARDBSeletCommand.ExecuteReader();
                    while (SelectResult.Read()) 
                    {
                        Console.WriteLine("Emp No" + " " + SelectResult.GetInt32(0));
                        Console.WriteLine("Emp Name" + " " + SelectResult.GetString(1));
                        if (SelectResult.IsDBNull(2) == false)
                            Console.WriteLine("Job" + " " + SelectResult.GetString(2));
                        else
                            Console.WriteLine("Job" + " null ");
                        if (SelectResult.IsDBNull(3) == false)
                            Console.WriteLine("Mgr" + " " + SelectResult.GetInt32(3));
                        else
                            Console.WriteLine("Mgr" + "null");
                        if (SelectResult.IsDBNull(4) == false)
                            Console.WriteLine("Hire Date" + " " + SelectResult.GetDateTime(4));
                        else
                            Console.WriteLine("Hire Date" + " null");
                        Console.WriteLine("---------------------------------");
                    }
    
                    //Insert statement using POLARDBCommand Object
                    SelectResult.Close();
                    POLARDBCommand POLARDBInsertCommand = new POLARDBCommand("INSERT INTO EMP(EMPNO,ENAME) VALUES((SELECT COUNT(EMPNO) FROM EMP),'JACKSON')",conn);
                    POLARDBInsertCommand.ExecuteScalar();
                    Console.WriteLine("Record inserted");
    
                    //Update  using POLARDBCommand Object
                    POLARDBCommand  POLARDBUpdateCommand = new POLARDBCommand("UPDATE EMP SET ENAME ='DOTNET' WHERE EMPNO < 100",conn);
                    POLARDBUpdateCommand.ExecuteNonQuery();
                    Console.WriteLine("Record has been updated");
                    POLARDBCommand POLARDBDeletCommand = new POLARDBCommand("DELETE FROM EMP WHERE EMPNO < 100",conn);
                    POLARDBDeletCommand.CommandType= CommandType.Text;
                    POLARDBDeletCommand.ExecuteScalar();
                    Console.WriteLine("Record deleted");
    
                    //procedure call example
                    try
                    {
                        POLARDBCommand callable_command = new POLARDBCommand("emp_query(:p_deptno,:p_empno,:p_ename,:p_job,:p_hiredate,:p_sal)", conn);
                        callable_command.CommandType = CommandType.StoredProcedure;
                        callable_command.Parameters.Add(new POLARDBParameter("p_deptno",POLARDBTypes.POLARDBDbType.Numeric,10,"p_deptno",ParameterDirection.Input,false ,2,2,System.Data.DataRowVersion.Current,20));
                        callable_command.Parameters.Add(new POLARDBParameter("p_empno", POLARDBTypes.POLARDBDbType.Numeric,10,"p_empno",ParameterDirection.InputOutput,false ,2,2,System.Data.DataRowVersion.Current,7369));
                        callable_command.Parameters.Add(new POLARDBParameter("p_ename", POLARDBTypes.POLARDBDbType.Varchar,10,"p_ename",ParameterDirection.InputOutput,false ,2,2,System.Data.DataRowVersion.Current,"SMITH"));
                        callable_command.Parameters.Add(new POLARDBParameter("p_job", POLARDBTypes.POLARDBDbType.Varchar,10,"p_job",ParameterDirection.Output,false ,2,2,System.Data.DataRowVersion.Current,null));
                        callable_command.Parameters.Add(new POLARDBParameter("p_hiredate", POLARDBTypes.POLARDBDbType.Date,200,"p_hiredate",ParameterDirection.Output,false ,2,2,System.Data.DataRowVersion.Current,null));
                        callable_command.Parameters.Add(new POLARDBParameter("p_sal", POLARDBTypes.POLARDBDbType.Numeric,200,"p_sal",ParameterDirection.Output,false ,2,2,System.Data.DataRowVersion.Current,null));
                        callable_command.Prepare();
                        callable_command.Parameters[0].Value = 20;
                        callable_command.Parameters[1].Value = 7369;
                        POLARDBDataReader result = callable_command.ExecuteReader();
                        int fc = result.FieldCount;
                        for(int i=0;i<fc;i++)
                            Console.WriteLine("RESULT["+i+"]="+ Convert.ToString(callable_command.Parameters[i].Value));
                        result.Close();
                    }
                    catch(POLARDBException exp)
                    {
                        if(exp.ErrorCode.Equals("01403"))
                            Console.WriteLine("No data found");
                        else if(exp.ErrorCode.Equals("01422"))
                            Console.WriteLine("More than one rows were returned by the query");
                        else
                            Console.WriteLine("There was an error Calling the procedure. \nRoot Cause:\n");
                        Console.WriteLine(exp.Message.ToString());
                    }
    
                    //Prepared statement
                    string updateQuery  = "update emp set ename = :Name where empno = :ID";
                    POLARDBCommand Prepared_command = new POLARDBCommand(updateQuery, conn);
                    Prepared_command.CommandType = CommandType.Text;
                    Prepared_command.Parameters.Add(new POLARDBParameter("ID", POLARDBTypes.POLARDBDbType.Integer));
                    Prepared_command.Parameters.Add(new POLARDBParameter("Name", POLARDBTypes.POLARDBDbType.Text));
                    Prepared_command.Prepare();
                    Prepared_command.Parameters[0].Value = 7369;
                    Prepared_command.Parameters[1].Value = "Mark";
                    Prepared_command.ExecuteNonQuery();
                    Console.WriteLine("Record Updated...");
                }
    
                catch(POLARDBException exp)
                {
                    Console.WriteLine(exp.ToString() );
                }
                finally
                {
                    conn.Close();
                }
    
            }
        }
    }

    ここで、コード文字列 Server=localhost;Port=1521;User Id=polaruser;Password=password;Database=sampledb はデータベースへの接続に使用される接続文字列です。

    接続文字列は、 Server Port User Id Password、および Database など、次の表で説明するパラメーターから構成されます。

    パラメーター 説明
    Server localhost ApsaraDB for POLARDB クラスターのエンドポイント。 エンドポイントをクエリする方法については、「エンドポイントの表示」をご参照ください。
    Port 1521 ApsaraDB for POLARDB クラスターのポート。 デフォルト値:1521。
    User Id polaruser ApsaraDB for POLARDB クラスターに接続するためのユーザー名。
    Password password ユーザー名のパスワード。
    Database sampledb 接続するデータベースの名前。