本文將介紹如何在C#應用中使用PolarDB .NET驅動連接PolarDB PostgreSQL版(兼容Oracle)數據庫。

前提條件

  • 已經在PolarDB集群創建用戶,如何創建用戶請參見創建數據庫賬號
  • 已經將需要訪問PolarDB集群的主機IP地址添加到白名單,如何添加白名單請參見設置集群白名單

背景信息

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版本協議 ,與.NETFramework 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驅動提供了PolarDB的EF5、EF6的dll,用于使用Entity Framework。

關于Entity Framework的更多介紹,請參見Entity Framework官網

安裝.NET驅動

  1. 下載.NET驅動
  2. 解壓.NET驅動。
    unzip polardb_oracle_.net.zip
  3. 將驅動導入到Visual Studio項目中。
    1. 在Visual Studio的GUI界面右鍵項目,單擊添加引用
    2. 引用管理器對話框,單擊瀏覽 > 瀏覽
      Visual Studio-1
    3. 選擇要引用的文件對話框,選中合適版本的驅動,單擊添加
      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;
    /*
     * 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=5432;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();
                    }
                    // 如果是.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 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();
                }
    
            }
        }
    }

連接串參數

當您連接數據庫時,應用程序需要提供連接字符串,字符串包含主機、用戶名、密碼等參數。

連接字符串的形式為keyword1=value; keyword2=value;,不區分大小寫,包含特殊字符(例如分號)的值可以使用雙引號("")。

以下是該驅動支持的連接字符串參數。

表 1. 基本連接
參數示例說明
HostlocalhostPolarDB集群的連接地址,如何查看連接地址請參見查看或申請連接地址
Port1521PolarDB集群的端口,默認為1521。
Databasesampledb需要連接的數據庫名稱。
UsernamepolaruserPolarDB集群的用戶名。
PasswordpasswordPolarDB集群用戶名對應的密碼。
表 2. 連接池
參數示例說明
Poolingtrue是否啟用連接池。
Minimum Pool Size0連接池的最小大小。
Maximum Pool Size100連接池的最大大小。
Connection Idle Lifetime300當連接數量超出Minimum Pool Size時,關閉多余閑置連接的超時時間(秒)。
Connection Pruning Interval10清理閑置連接的間隔(秒)。
表 3. 其他參數
參數說明
application_name應用程序名稱。
search_pathSchema的搜索路徑。
client_encoding客戶端編碼。
timezone會話的時區。