このトピックでは、PolarDB .NET ドライバーを使用して C# アプリケーションを PolarDB for PostgreSQL (Compatible with Oracle) データベースに接続する方法について説明します。
前提条件
-
PolarDB クラスターでデータベースアカウントを作成済みであること。詳細については、「データベースアカウントの作成」をご参照ください。
-
PolarDB クラスターへのアクセスが必要なホストの IP アドレスがホワイトリストに追加されていること。詳細については、「クラスターホワイトリストの設定」をご参照ください。
背景情報
PolarDB .NET (別名、PolarDB 用 ADO.NET データプロバイダー) は、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 は、.NET プラットフォームで人気のあるオブジェクトリレーショナルマッピング (ORM) フレームワークです。C# でバックエンドアプリケーションを記述する際、Entity Framework と統合言語クエリ (LINQ) は開発を大幅に加速できます。
PolarDB .NET ドライバーは、Entity Framework 5 (EF5) と Entity Framework 6 (EF6) をサポートする DLL を提供します。
Entity Framework の詳細については、「Entity Framework 公式ウェブサイト」をご参照ください。
.NET ドライバーのインストール
-
.NET ドライバーをダウンロードします。
-
.NET ドライバーパッケージを解凍します。
unzip polardb_oracle_.net.zip -
ドライバーを Visual Studio プロジェクトにインポートします。
-
Visual Studio の UI で、プロジェクトを右クリックし、[参照の追加] を選択します。
-
[参照マネージャー] ダイアログボックスで、[参照] をクリックします。
[参照...] ボタンを使用して、参照するファイルを選択します。
-
[参照するファイルの選択] ダイアログボックスで、適切なドライバーのバージョンを選択し、追加する をクリックします。
たとえば、.NET Framework 4.5 (net45 フォルダー) を使用している場合は、
PolarDB.PolarDBClient.dll、System.Runtime.CompilerServices.Unsafe.dll、System.Threading.Tasks.Extensions.dll、System.ValueTuple.dllの 4 つの DLL ファイルを参照する必要があります。 -
確定 をクリックします。
-
例
サンプルプロジェクトを実行するには、次の手順に従ってください。
-
データベースクラスターに接続します。詳細については、「データベースクラスターへの接続」をご参照ください。
-
次のコマンドを実行して、
sampledbという名前のデータベースを作成します。CREATE DATABASE sampledb; -
サンプルに必要なテーブル、データ、および関数を
sampledbデータベースにインポートします。\i ${your path}/PolarDBSample.sql -
データがインポートされたら、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("More than one row was 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 = "田中"; Prepared_command.ExecuteNonQuery(); Console.WriteLine("Record Updated..."); } catch(PolarDBException exp) { Console.WriteLine(exp.ToString() ); } finally { conn.Close(); } } } }
接続文字列パラメーター
アプリケーションがデータベースに接続する際には、ホスト、ユーザー名、パスワードなどのパラメーターを含む接続文字列を指定する必要があります。
接続文字列の形式は keyword1=value; keyword2=value; です。キーワードでは、大文字と小文字は区別されません。セミコロンなどの特殊文字を含む値は、二重引用符 ("") で囲みます。
このドライバーは、次の接続文字列パラメーターをサポートしています。
表 1. 基本接続
|
パラメーター |
例 |
説明 |
|
Host |
|
PolarDB クラスターのエンドポイント。詳細については、「エンドポイントの表示または申請」をご参照ください。 |
|
Port |
|
PolarDB クラスターのデフォルトポートは 5432 です。 |
|
Database |
|
接続するデータベースの名前。 |
|
Username |
|
PolarDB クラスターのユーザー名。 |
|
Password |
|
PolarDB クラスターのユーザー名のパスワード。 |
表 2. 接続プール
|
パラメーター |
例 |
説明 |
|
Pooling |
|
接続プールを有効にするかどうかを指定します。 |
|
Minimum Pool Size |
0 |
プールに保持する接続の最小数。 |
|
Maximum Pool Size |
100 |
プールで許可される接続の最大数。 |
|
Connection Idle Lifetime |
300 |
タイムアウト (秒単位)。この期間が経過すると、プールサイズが |
|
Connection Pruning Interval |
10 |
アイドル状態の接続がプールからプルーニングされる間隔 (秒単位)。 |
表 3. その他のパラメーター
|
パラメーター |
説明 |
|
Application name |
アプリケーション名。 |
|
Search path |
スキーマの検索パス。 |
|
Client Encoding |
クライアントエンコーディング。 |
|
Timezone |
セッションのタイムゾーン。 |