The ADO.NET Data Provider for PolarDB for PostgreSQL (Compatible with Oracle) — also called PolarDB .NET — lets you connect C#, Visual Basic, and F# applications to PolarDB for PostgreSQL (Compatible with Oracle) databases. The driver supports Entity Framework Core and Entity Framework 6.x, so you can use object-relational mapping (ORM) alongside Language-Integrated Query (LINQ) to build backend applications faster.
Prerequisites
Before you begin, make sure you have:
A database account for your PolarDB cluster. See Create database accounts
The IP address of your application host added to the cluster whitelist. See Configure a whitelist for a cluster
Quick start
The following example connects to a PolarDB database, runs a SELECT query, and prints the results.
using System;
using PolarDB.PolarDBClient;
namespace PolarDBClientTest
{
class Program
{
static void Main(string[] args)
{
// Replace the values with your cluster endpoint, port, credentials, and database name
var conn = new PolarDBConnection(
"Server=<your-endpoint>;Port=5432;User Id=<your-username>;Password=<your-password>;Database=<your-database>");
try
{
conn.Open();
var cmd = new PolarDBCommand("SELECT EMPNO, ENAME FROM EMP", conn);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine($"EmpNo: {reader.GetInt32(0)}, Name: {reader.GetString(1)}");
}
reader.Close();
}
catch (PolarDBException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
conn.Close();
}
}
}
}Replace the following placeholders:
| Placeholder | Description | Example |
|---|---|---|
<your-endpoint> | Cluster endpoint. See View or apply for an endpoint. | pc-xxx.polardb.rds.aliyuncs.com |
<your-username> | Database account username | polaruser |
<your-password> | Password for the account | — |
<your-database> | Name of the target database | sampledb |
Compatibility
PolarDB .NET uses version 3.0 of the PostgreSQL protocol. It is compatible with:
.NET Framework 2.0, 4.0, and 4.5
.NET Core 2.0
Class name migration: In earlier driver versions, class names start with POLARDB. The latest version uses PolarDB. Replace POLARDB with PolarDB throughout your code. The driver logic is unchanged, so services are not affected after the upgrade.
Entity Framework
PolarDB .NET provides the .dll files for Entity Framework 5 (EF5) and Entity Framework 6 (EF6), which are applicable to PolarDB for PostgreSQL (Compatible with Oracle). This makes it straightforward to use Entity Framework with your PolarDB applications.
For more information about Entity Framework, see the official Entity Framework documentation.
Install the PolarDB .NET driver
Download the PolarDB .NET driver package.
Decompress the package.
unzip polardb_oracle_.net.zipImport the driver into your Visual Studio project.
In the left-side navigation pane, right-click Projects and select Add Reference.
In the Reference Manager dialog box, click Browse in the left pane, then click Browse....
In the Select the files to reference dialog box, select the driver file and click Add.
Click OK.


Run sample code
The driver package includes a Samples directory with a PolarDBSample.sql file and several sample project files.
Create a test database.
CREATE DATABASE sampledb;Import the sample tables, data, and functions into
sampledb.\i ${your path}/PolarDBSample.sqlRun the C# sample code shown in the following sections.
All examples use classes from the PolarDB.PolarDBClient namespace and a shared connection conn.
Query data
Use PolarDBCommand and PolarDBDataReader to run a SELECT statement and read each row.
using System;
using System.Data;
using PolarDB.PolarDBClient;
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();
// Query — read employee records
PolarDBCommand selectCmd = new PolarDBCommand(
"SELECT EMPNO,ENAME,JOB,MGR,HIREDATE FROM EMP", conn);
PolarDBDataReader reader = selectCmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("Emp No" + " " + reader.GetInt32(0));
Console.WriteLine("Emp Name" + " " + reader.GetString(1));
if (reader.IsDBNull(2) == false)
Console.WriteLine("Job" + " " + reader.GetString(2));
else
Console.WriteLine("Job" + " null ");
if (reader.IsDBNull(3) == false)
Console.WriteLine("Mgr" + " " + reader.GetInt32(3));
else
Console.WriteLine("Mgr" + "null");
if (reader.IsDBNull(4) == false)
Console.WriteLine("Hire Date" + " " + reader.GetDateTime(4));
else
Console.WriteLine("Hire Date" + " null");
Console.WriteLine("---------------------------------");
}
reader.Close();
}
catch (PolarDBException exp)
{
Console.WriteLine(exp.ToString());
}
finally
{
conn.Close();
}
}
}
}Insert data
Use ExecuteScalar() to run an INSERT statement.
// Insert — add a new employee row
PolarDBCommand insertCmd = new PolarDBCommand(
"INSERT INTO EMP(EMPNO,ENAME) VALUES((SELECT COUNT(EMPNO) FROM EMP),'JACKSON')", conn);
insertCmd.ExecuteScalar();
Console.WriteLine("Record inserted");Update data
Use ExecuteNonQuery() to run an UPDATE statement.
// Update — rename employees with EMPNO < 100
PolarDBCommand updateCmd = new PolarDBCommand(
"UPDATE EMP SET ENAME='DOTNET' WHERE EMPNO < 100", conn);
updateCmd.ExecuteNonQuery();
Console.WriteLine("Record has been updated");Delete data
Use ExecuteScalar() to run a DELETE statement.
// Delete — remove employees with EMPNO < 100
PolarDBCommand deleteCmd = new PolarDBCommand(
"DELETE FROM EMP WHERE EMPNO < 100", conn);
deleteCmd.CommandType = CommandType.Text;
deleteCmd.ExecuteScalar();
Console.WriteLine("Record deleted");Call a stored procedure
Set CommandType to StoredProcedure and bind parameters with PolarDBParameter. Error codes 01403 (no data found) and 01422 (multiple rows returned) are handled in the catch block.
// Stored procedure call — query employee details
try
{
PolarDBCommand callCmd = new PolarDBCommand(
"emp_query(:p_deptno,:p_empno,:p_ename,:p_job,:p_hiredate,:p_sal)", conn);
callCmd.CommandType = CommandType.StoredProcedure;
callCmd.Parameters.Add(new PolarDBParameter("p_deptno", PolarDBTypes.PolarDBDbType.Numeric, 10, "p_deptno", ParameterDirection.Input, false, 2, 2, System.Data.DataRowVersion.Current, 20));
callCmd.Parameters.Add(new PolarDBParameter("p_empno", PolarDBTypes.PolarDBDbType.Numeric, 10, "p_empno", ParameterDirection.InputOutput, false, 2, 2, System.Data.DataRowVersion.Current, 7369));
callCmd.Parameters.Add(new PolarDBParameter("p_ename", PolarDBTypes.PolarDBDbType.Varchar, 10, "p_ename", ParameterDirection.InputOutput, false, 2, 2, System.Data.DataRowVersion.Current, "SMITH"));
callCmd.Parameters.Add(new PolarDBParameter("p_job", PolarDBTypes.PolarDBDbType.Varchar, 10, "p_job", ParameterDirection.Output, false, 2, 2, System.Data.DataRowVersion.Current, null));
callCmd.Parameters.Add(new PolarDBParameter("p_hiredate",PolarDBTypes.PolarDBDbType.Date, 200, "p_hiredate",ParameterDirection.Output, false, 2, 2, System.Data.DataRowVersion.Current, null));
callCmd.Parameters.Add(new PolarDBParameter("p_sal", PolarDBTypes.PolarDBDbType.Numeric,200, "p_sal", ParameterDirection.Output, false, 2, 2, System.Data.DataRowVersion.Current, null));
callCmd.Prepare();
callCmd.Parameters[0].Value = 20;
callCmd.Parameters[1].Value = 7369;
PolarDBDataReader result = callCmd.ExecuteReader();
int fc = result.FieldCount;
for (int i = 0; i < fc; i++)
Console.WriteLine("RESULT[" + i + "]=" + Convert.ToString(callCmd.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());
}
}Note: If you are using the .NET 2.0 driver, modify the catch block as needed.
Use prepared statements
Parameterized queries protect against SQL injection and improve performance through statement reuse. Use named parameters (:Name, :ID) with PolarDBParameter.
// Prepared statement — update employee name by ID
string updateQuery = "update emp set ename = :Name where empno = :ID";
PolarDBCommand preparedCmd = new PolarDBCommand(updateQuery, conn);
preparedCmd.CommandType = CommandType.Text;
preparedCmd.Parameters.Add(new PolarDBParameter("ID", PolarDBTypes.PolarDBDbType.Integer));
preparedCmd.Parameters.Add(new PolarDBParameter("Name", PolarDBTypes.PolarDBDbType.Text));
preparedCmd.Prepare();
preparedCmd.Parameters[0].Value = 7369;
preparedCmd.Parameters[1].Value = "Mark";
preparedCmd.ExecuteNonQuery();
Console.WriteLine("Record Updated...");Connection string parameters
Connection strings follow the keyword1=value; keyword2=value; format and are case-insensitive. Enclose values that contain special characters such as semicolons (;) in double quotation marks (").
Basic connection
| Parameter | Description | Default |
|---|---|---|
Host | Cluster endpoint. See View or apply for an endpoint. | Required |
Port | Cluster port. | 1521 |
Database | Name of the database to connect to. | Required |
Username | Account username. | Required |
Password | Account password. | Required |
Connection pool
| Parameter | Description | Default |
|---|---|---|
Pooling | Enables or disables the connection pool. | true |
Minimum Pool Size | Minimum number of connections in the pool. | 0 |
Maximum Pool Size | Maximum number of connections in the pool. | 100 |
Connection Idle Lifetime | Time in seconds before idle connections are closed when the pool size exceeds Minimum Pool Size. | 300 |
Connection Pruning Interval | Interval in seconds between idle connection cleanup runs. | 10 |
Session and application settings
| Parameter | Description | Default |
|---|---|---|
application_name | Name of the application. | — |
search_path | Search path for the schema. | — |
client_encoding | Client character encoding. | — |
timezone | Session time zone. | — |