すべてのプロダクト
Search
ドキュメントセンター

PolarDB:.NET

最終更新日:May 16, 2026

このトピックでは、C# アプリケーションで PolarDB .NET ドライバーを使用して データベースに接続する方法について説明します。

前提条件

背景情報

PolarDB .NET (ADO.NET Data Provider for PolarDB とも呼ばれます) は、C#、Visual Basic、F# などの言語を使用して PolarDB にアクセスするためのドライバーです。 Entity Framework Core および Entity Framework 6.x と互換性があります。 このドライバーを Entity Framework と共に使用して、アプリケーション開発を高速化できます。

このドライバーは PostgreSQL プロトコルのバージョン 3.0 を使用しており、.NET Framework 2.0、.NET Framework 4.0、.NET Framework 4.5、および .NET Core 2.0 と互換性があります。

以前のバージョンの PolarDB .NET ドライバーでは、多くのクラス名が POLARDB で始まっていました。 このプレフィックスは PolarDB に変更されました。 古いプレフィックスを置き換えてコードを更新する必要があります。 ドライバーのロジックは変更されていないため、安心してアップグレードできます。

Entity Framework

Entity Framework と統合言語クエリ (LINQ) を使用すると、C# バックエンドアプリケーションの開発を大幅に高速化できます。

PolarDB .NET ドライバーは、Entity Framework で使用するための EF5 および EF6 の .dll ファイルを提供します。

Entity Framework の詳細については、「Entity Framework の公式サイト」をご参照ください。

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

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

  2. .NET ドライバー パッケージを解凍します。

    unzip polardb_oracle_.net.zip
  3. ドライバーを Visual Studio プロジェクトにインポートします。

    1. Visual Studio でプロジェクトを右クリックし、[参照の追加] をクリックします。

    2. [参照マネージャー] ダイアログボックスで、[参照] をクリックします。

      Visual Studio-1

    3. [参照するファイルの選択] ダイアログボックスで、適切なドライバーのバージョンを選択し、Add をクリックします。

      Visual Studio-2

    4. 確定 をクリックします。

Samples ディレクトリには、PolarDBSample.sql ファイルといくつかのサンプルプロジェクト ファイルが含まれています。 以下の手順では、これらのサンプルプロジェクトの実行方法を示します。

  1. データベースに接続します。 詳細については、「データベースクラスターへの接続」をご参照ください。

  2. 次のコマンドを実行して、sampledb という名前のデータベースを作成します。

    CREATE DATABASE sampledb;
  3. サンプルスキーマとデータを sampledb データベースにインポートします。

    \i ${your path}/PolarDBSample.sql
  4. データがインポートされた後、C# コードの記述を開始できます。

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

    using System;
    using System.Data;
    using PolarDB.PolarDBClient;
    /*
     * このクラスは、PolarDB で DML 操作を実行する方法を説明します。
     *
     * @revision 1.0
     */
    
    namespace PolarDBClientTest
    {
    
        class SAMPLE_TEST
        {
    
            static void Main(string[] args)
            {
                PolarDBConnection conn = new PolarDBConnection("Server=localhost;Port=5432;User Id=polaruser;Password=password;Database=sampledb");
                try
                {
                    conn.Open();
    
                    // PolarDBCommand オブジェクトを使用した単純な SELECT ステートメント
                    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("---------------------------------");
                    }
    
                    // PolarDBCommand オブジェクトを使用して INSERT ステートメントを実行します。
                    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");
    
                    // PolarDBCommand オブジェクトを使用してレコードを更新します。
                    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");
    
                    // ストアドプロシージャの呼び出し例
                    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();
                    }
                    // .NET 2.0 ドライバーを使用している場合は、このセクションを適宜変更する必要があります。
                    catch(PolarDBException exp)
                    {
                        if(exp.ErrorCode.Equals("01403"))
                            Console.WriteLine("No data found");
                        else if(exp.ErrorCode.Equals("01422"))
                            Console.WriteLine("Multiple rows were returned by the query");
                        else
                            Console.WriteLine("There was an error calling the procedure. \nRoot Cause:\n");
                        Console.WriteLine(exp.Message.ToString());
                    }
    
                    // プリペアドステートメント
                    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();
                }
    
            }
        }
    }

接続文字列のパラメーター

アプリケーションは、ホスト、ユーザー名、パスワードなどのパラメーターを含む接続文字列を提供することで、データベースに接続します。

接続文字列は keyword1=value; keyword2=value; 形式を使用し、大文字と小文字は区別されません。 セミコロンなどの特殊文字を含む値は、二重引用符 ("") で囲んでください。

次の表に、このドライバーでサポートされている接続文字列のパラメーターを示します。

表 1. 基本的な接続パラメーター

パラメーター

説明

Host

localhost

PolarDB クラスターのエンドポイント。 エンドポイントの表示方法の詳細については、「エンドポイントの表示または申請」をご参照ください。

Port

5432

PolarDB クラスターのポート。 デフォルト値は 5432 です。

Database

sampledb

接続先のデータベースの名前。

Username

polaruser

PolarDB クラスターのユーザー名。

Password

password

PolarDB クラスターで指定したユーザーのパスワード。

表 2. 接続プールのパラメーター

パラメーター

説明

Pooling

true

接続プールを有効にするかどうかを指定します。

Min Pool Size

0

接続プールで維持する接続の最小数。

Max Pool Size

100

接続プールで許可される接続の最大数。

Connection Idle Lifetime

300

接続数が Min Pool Size を超えた場合に、アイドル状態の接続を閉じるまでのタイムアウト期間 (秒単位)。

Connection Pruning Interval

10

アイドル接続をプルーニングする間隔 (秒単位)。

表 3. その他のパラメーター

パラメーター

説明

application_name

アプリケーションの名前。

search_path

スキーマ検索パス。

client_encoding

クライアントが使用する文字エンコーディング。

timezone

現在のセッションのタイムゾーン。