本文将介绍如何在C#应用中使用POLARDB .NET驱动连接POLARDB数据库。

前提条件

  • 已经在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 4.x,.NET Core 2.x兼容。

Entity Framework简介

Entity Framework是.NET平台上流行的ORM框架。在使用C#编写后端应用时,Entity Framework以及Linq技术极大地加速了后端应用的开发。

POLARDB .NET驱动提供了POLARDB的EF5、EF6的dll,用于使用Entity Framework。

关于Entity Framework的更多介绍,请参见Entity Framework官网https://docs.microsoft.com/zh-cn/ef/

下载.NET驱动

您可以单击这里下载.NET驱动。

安装.NET驱动

  1. 解压.NET驱动。
    unzip POLARDB-for-Oracle-.net_installer.zip
  2. 将驱动导入到Visual Studio项目中。

    您需要在sample.csproj的<Project>节点或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. 连接数据库,具体操作请参见连接数据库集群
  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 POLARDB集群的连接地址,如何查看连接地址请参见查看连接地址
    Port 1521 POLARDB集群的端口,默认为1521。
    User Id polaruser POLARDB集群的用户名。
    Password password POLARDB集群用户名对应的密码。
    Database sampledb 需要连接的数据库名称。