EDB Postgres Advanced Server NET Connector Guide v11.0.2
EDB Postgres Advanced Server NET Connector Guide v11.0.2
April 2, 2019
EDB Postgres™ Advanced Server .NET Connector Guide
by EnterpriseDB® Corporation
Copyright © 2009 - 2019 EnterpriseDB Corporation. All rights reserved.
Table of Contents
1 Introduction ................................................................................................................. 5
1.1 Typographical Conventions Used in this Guide ................................................. 6
2 Requirements Overview.............................................................................................. 7
2.1 Supported Platforms............................................................................................ 7
3 The Advanced Server .NET Connector - Overview ................................................... 8
3.1 The .NET Class Hierarchy .................................................................................. 8
4 Installing and Configuring the .NET Connector ......................................................... 9
4.1 Installing the .Net Connector .............................................................................. 9
4.2 Configuring the .NET Connector ...................................................................... 13
4.2.1 Referencing the Library Files ....................................................................... 14
4.2.2 .NET Framework Setup ................................................................................ 15
4.2.2.1 NET Framework 4.0 ............................................................................. 16
4.2.2.2 .NET Framework 4.5 ............................................................................ 17
4.2.2.3 .NET Framework 4.5.1 ......................................................................... 18
4.2.2.4 .NET Standard 2.0................................................................................. 19
4.2.3 Entity Framework 5/6 ................................................................................... 20
4.2.4 EnterpriseDB VSIX for Visual Studio 2015/2017........................................ 22
4.2.4.1 Installation and Configuration for Visual Studio 2015/2017 ................ 23
4.2.4.2 Model First and Database First Usage .................................................. 24
5 Using the .NET Connector ........................................................................................ 26
5.1 Opening a Database Connection ....................................................................... 26
5.1.1 Connection String Parameters....................................................................... 27
5.1.2 Example - Opening a Database Connection using ASP.NET....................... 30
5.1.3 Example - Opening a Database Connection from a Console Application .... 31
5.1.4 Example - Opening a Database Connection from a Windows Form
Application ................................................................................................................ 33
5.2 Retrieving Database Records ............................................................................ 35
5.2.1 Retrieving a Single Database Record ........................................................... 37
5.3 Parameterized Queries ...................................................................................... 38
5.4 Inserting Records in a Database ........................................................................ 40
5.5 Deleting Records in a Database ........................................................................ 42
5.6 Using SPL Stored Procedures in your .NET Application ................................. 44
1 Introduction
The EDB Postgres™ Advanced Server .NET Connector distributed with EDB Postgres™
Advanced Server (Advanced Server) provides connectivity between a .NET client
application and an Advanced Server database server. This guide provides installation
instructions, usage instructions, and examples that demonstrate the functionality of the
Advanced Server .NET Connector:
This document assumes that you have a solid working knowledge of both C# and .NET.
The Advanced Server .NET Connector functionality is built on the core functionality of
the Npgsql open source project. The Npgsql User's Manual is available online at:
http://www.npgsql.org/doc/index.html
In the following descriptions a term refers to any word or group of words that are
language keywords, user-supplied values, literals, etc. A term’s exact meaning depends
upon the context in which it is used.
Italic font introduces a new term, typically, in the sentence that defines it for the
first time.
Fixed-width (mono-spaced) font is used for terms that must be given
literally such as SQL commands, specific table and column names used in the
examples, programming language keywords, etc. For example, SELECT * FROM
emp;
Italic fixed-width font is used for terms for which the user must
substitute values in actual usage. For example, DELETE FROM table_name;
A vertical pipe | denotes a choice between the terms on either side of the pipe. A
vertical pipe is used to separate two or more alternative terms within square
brackets (optional choices) or braces (one mandatory choice).
Square brackets [ ] denote that one or none of the enclosed term(s) may be
substituted. For example, [ a | b ], means choose one of “a” or “b” or neither
of the two.
Braces {} denote that exactly one of the enclosed alternatives must be specified.
For example, { a | b }, means exactly one of “a” or “b” must be specified.
Ellipses ... denote that the proceeding term may be repeated. For example, [ a |
b ] ... means that you may have the sequence, “b a a b a”.
2 Requirements Overview
The following section details the supported platforms for the Advanced Server .NET
Connector.
64-bit Windows:
32-bit Windows:
Windows 10
Windows 8
Windows 7
The .NET Connector supports .NET Framework versions 4.0 and 4.5.1, and Entity
Framework 5/6, and .Net Standard 2.0.
EDBConnection
EDBCommand
An EDBCommand object contains an SQL command that the client will execute
against Advanced Server. Before you can execute an EDBCommand object, you
must link it to an EDBConnection object.
EDBDataReader
EDBDataAdapter
https://www.enterprisedb.com/advanced-downloads
After downloading the installer, right-click on the installer icon, and select Run As
Administrator from the context menu.
When the Language Selection popup opens, select an installation language and click
OK to continue to the Setup window (shown in Figure 2.1).
Use the Installation Directory dialog (see Figure 2.2) to specify the directory in
which the connector will be installed, and click Next to continue.
Click Next on the Ready to Install dialog (see Figure 2.3) to start the installation;
popup dialogs confirm the progress of the installation wizard.
When the wizard informs you that it has completed the setup, click the Finish button to
exit the dialog (see Figure 2.4).
You can use StackBuilder Plus to add or update the connector on an existing Advanced
Server installation; to open StackBuilder Plus, select StackBuilder Plus from the
Windows Apps menu (see Figure 2.5).
When StackBuilder Plus opens, follow the onscreen instructions. Select the
EnterpriseDB .Net Connector option from the Database Drivers node of the
tree control (see Figure 2.6).
Follow the directions of the onscreen wizard to add or update an installation of the
EnterpriseDB Connectors.
.NET Framework 4.0. Instructions for configuring for usage with .NET
Framework 4.0.
.NET Framework 4.5. Instructions for configuring for usage with .NET
Framework 4.5.
.NET Framework 4.5.1. Instructions for configuring for usage with .NET
Framework 4.5.1.
.NET Standard 2.0. Instructions for configuring for usage with .NET Standard
2.0.
Entity Framework 5/6. Instructions for configuring for usage with Entity
Framework.
Before you can use an Advanced Server .NET class, you must import the namespace into
your program. Importing a namespace makes the compiler aware of the classes available
within the namespace. The namespace is the following:
EnterpriseDB.EDBClient
If you are using Entity Framework 6, the additional namespace is the following:
EntityFramework6.EntepriseDB.EDBClient
The method you use to include the namespace varies by the type of application you are
writing. For example, the following command imports a namespace into an ASP.NET
page:
using EnterpriseDB.EDBClient;
The following sections describe the setup for various .NET versions.
C:\Program Files\edb\dotnet\net40\
EDBDataProvider.2.0.2.dll
Mono.Security.dll
Depending upon the type of application, import the namespace into the source code (see
Section 4.2.1).
C:\Program Files\edb\dotnet\net45\
EnterpriseDB.EDBClient.dll
System.Threading.Tasks.Extensions.dll
System.Runtime.CompilerServices.Unsafe.dll
System.ValueTuple.dll
Note: You must also add the following dependencies to your project:
System.Threading.Tasks.Extensions.dll
System.Runtime.CompilerServices.Unsafe.dll
System.ValueTuple.dll
Depending upon the type of application, import the namespace into the source code (see
Section 4.2.1).
C:\Program Files\edb\dotnet\net451\
EnterpriseDB.EDBClient.dll
System.Threading.Tasks.Extensions.dll
System.Runtime.CompilerServices.Unsafe.dll
System.ValueTuple.dll
Note: You must also add the following dependencies to your project:
System.Threading.Tasks.Extensions.dll
System.Runtime.CompilerServices.Unsafe.dll
System.ValueTuple.dll
Depending upon the type of application, import the namespace into the source code (see
Section 4.2.1).
C:\Program Files\edb\dotnet\netstandard2.0\
EnterpriseDB.EDBClient.dll
System.Threading.Tasks.Extensions.dll
System.Runtime.CompilerServices.Unsafe.dll
System.ValueTuple.dll
Note: You must also add the following dependencies to your project:
System.Runtime.CompilerServices.Unsafe.dll
System.ValueTuple.dll
Note: If your target framework is .Net Core 2.0, then include the following file in your
project:
System.Threading.Tasks.Extensions.dll
Depending upon the application type, import the namespace into the source code (see
Section 4.2.1).
To set up .NET Connector for usage with Entity Framework, the data provider
installation path is:
C:\Program Files\edb\dotnet\EF\
EntityFramework5.EnterpriseDB.EDBClient.dll
EntityFramework6.EnterpriseDB.EDBClient.dll
Add the <DbProviderFactories> entries for the ADO.NET driver of EDB Postgres
in the app.config file. The following are the entries:
<add name="EnterpriseDB.EDBClient"
invariant="EnterpriseDB.EDBClient"
description=".NET Data Provider for EnterpriseDB
PostgreSQL”
type="EnterpriseDB.EDBClient.EDBFactory,
EnterpriseDB.EDBClient, Version=4.0.4.1, Culture=neutral,
PublicKeyToken=5d8b90d52f46fda7"
support="FF"/>
In the project’s app.config file add the following entry for provider services under the
EntityFramework/providers tag.
<provider invariantName="EnterpriseDB.EDBClient"
type="EnterpriseDB.EDBClient.EDBServices,
EntityFramework6.EnterpriseDB.EDBClient">
</provider>
<startup>
<entityFramework>
<providers>
<provider invariantName="EnterpriseDB.EDBClient"
type="EnterpriseDB.EDBClient.EDBServices,
EntityFramework6.EnterpriseDB.EDBClient"></provider>
</providers>
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant="EnterpriseDB.EDBClient"/>
<add name="EnterpriseDB Data Provider" invariant="EnterpriseDB.EDBClient"
support="FF" description=".Net Framework Data Provider for Postgresql"
type="EnterpriseDB.EDBClient.EDBFactory, EnterpriseDB.EDBClient"/>
</DbProviderFactories>
</system.data>
</configuration>
Note: The same entries for <providers> and <DbProviderFactories> are valid for
the web.config file as well as for app.config.
Depending upon the type of application, import the namespace into the source code (see
Section 4.2.1).
For usage of the features of Entity Framework, refer to the Microsoft documentation.
It allows connecting to Advanced Server from within Visual Studio's Server Explorer,
creating a model from an existing database, etc. Therefore, if Visual Studio features are
desired, then EnterpriseDB VSIX must be utilized.
C:\Program Files\edb\dotnet\vsix\
EnterpriseDB.vsix
SSDLToPgSQL.tt
Step 1: Install EnterpriseDB VSIX to the desired version of Visual Studio with the
EnterpriseDB.vsix installer at the following location:
C:\Program Files\edb\dotnet\vsix\
EnterpriseDB.vsix
If you already have an earlier version of the VSIX installed, it’s highly recommended that
you uninstall them to avoid conflicts.
Step 2: Relaunch Visual Studio and verify from Tools > Extensions and
Updates… menu that the EnterpriseDB extension is installed.
C:\Program Files\edb\dotnet\vsix\System.ValueTuple.dll
For example:
> gacutil.exe /i System.ValueTuple.dll
For example:
Step 2: Add the <DbProviderFactories> entries for the ADO.NET driver of EDB
Postgres in the machine.config file. The following are the entries:
<add name="EnterpriseDB.EDBClient"
invariant="EnterpriseDB.EDBClient"
description=".NET Data Provider for EnterpriseDB
PostgreSQL"
type="EnterpriseDB.EDBClient.EDBFactory,
EnterpriseDB.EDBClient, Version=4.0.4.1, Culture=neutral,
PublicKeyToken=5d8b90d52f46fda7"
support="FF"/>
Note: For the attribute-value pairs, the double-quoted strings should not contain excess
white space characters, but be configured on a single line. The examples shown in this
section may be split on multiple lines for clarity, but should actually be configured within
a single line such as the following:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\
Config\machine.config
C:\Windows\Microsoft.NET\Framework\v4.0.30319\
Config\machine.config
Step 3: Place the DDL generation template SSDLToPgSQL.tt in the Visual Studio
EntityFramework Tools\DBGen\ folder as in the following example:
Step 5: In the project’s app.config file add the following entry for provider services
under the EntityFramework/providers tag.
<provider invariantName="EnterpriseDB.EDBClient"
type="EnterpriseDB.EDBClient.EDBServices,
EntityFramework6.EnterpriseDB.EDBClient">
</provider>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<providers>
<provider invariantName="EnterpriseDB.EDBClient"
type="EnterpriseDB.EDBClient.EDBServices,
EntityFramework6.EnterpriseDB.EDBClient"></provider>
</providers>
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant="EnterpriseDB.EDBClient"/>
<add name="EnterpriseDB Data Provider" invariant="EnterpriseDB.EDBClient"
support="FF" description=".Net Framework Data Provider for EDB Postgres"
type="EnterpriseDB.EDBClient.EDBFactory, EnterpriseDB.EDBClient"/>
</DbProviderFactories>
</system.data>
</configuration>
To use the examples in this guide, place the .NET library files in the same directory as
the compiled form of your application. All of the examples are written in C# and each is
embedded in an ASP.NET page; the same logic and code would be applicable with other
.NET applications (WinForm or console applications, for example).
Please create and save the following web.config file in the same directory as the
sample code. The examples make use of the DB_CONN_STRING key from this
configuration file to return a connection string from the Advanced Server host.
An Advanced Server connection string for an ASP.NET web application is stored in the
web.config file. If you are writing an application that does not use ASP.NET, provide
the connection information in an application configuration file (such as app.config).
The examples that follow demonstrate the basic steps for connecting to an instance of
Advanced Server. You must:
4. Call the Open method of the EDBConnection object to open the connection.
A valid connection string should specify location and authentication information for an
Advanced Server instance. You must provide the connection string before opening the
connection. A connection string must contain:
CommandTimeout
ConnectionLifeTime
Database
Use the Database parameter to specify the name of the database to which the
application should connect. If a database name is not specified, the database
name will default to the name of the connecting user.
Encoding
The Encoding parameter is obsolete; the parameter always returns the string
unicode, and silently ignores attempts to set it.
Integrated Security
MaxPoolSize
MinPoolSize
Password
When using clear text authentication, specify the password that will be used to
establish a connection with the server.
Pooling
Port
The Port parameter specifies the port to which the application should connect.
Protocol
SearchPath
Use the SearchPath parameter to change the search path to named and public
schemas.
Server
SSL
sslmode
Use sslmode to specify an SSL connection control preference. sslmode can be:
SyncNotification
Timeout
Timeout specifies the length of time (in seconds) to wait for an open connection.
The default value is 15.
User Id
The User Id parameter specifies the user name that should be used for the
connection.
try
{
conn.Open();
Response.Write("Connection opened successfully");
}
catch(EDBException exp)
{
exp.ToString();
}
finally
{
conn.Close();
}
}
</script>
The following example opens a connection with an Advanced Server database using a
console-based application.
Before writing the code for the console application, create an app.config file that
stores the connection string to the database. Using a configuration file makes it
convenient to update the connection string if the information changes.
Using your text editor of choice, enter the following code sample into a file:
using System;
using System.Data;
using EnterpriseDB.EDBClient;
using System.Configuration;
namespace EnterpriseDB
{
class EDB
{
try
{
conn.Open();
Console.WriteLine("Connection Opened Successfully");
}
catch(Exception exp)
{
throw new Exception(exp.ToString());
}
finally
{
conn.Close();
}
}
}
}
Compiling the sample should generate a Console.exe file; you can execute the sample
code by entering Console.exe. When executed, the console should verify that the:
using System;
using System.Windows.Forms;
using System.Drawing;
using EnterpriseDB.EDBClient;
namespace EDBTestClient
{
class Win_Conn
{
static void Main(string[] args)
{
Form frmMain = new Form();
Button btnConn = new Button();
btnConn.Location = new System.Drawing.Point(104, 64);
btnConn.Name = "btnConn";
btnConn.Text = "Open Connection";
btnConn.Click += new System.EventHandler(btnConn_Click);
frmMain.Controls.Add(btnConn);
frmMain.Text = "EnterpriseDB";
Application.Run(frmMain);
}
}
catch(EDBException exp)
{
MessageBox.Show(exp.ToString());
}
finally
{
conn.Close();
}
}
}
}
Note that you must change the database connection string to point to the database that
you want to connect to before compiling the file with the following command:
This command should generate a WinForm.exe file within the same folder that the
executable was compiled under. Invoking the executable will display:
You can use a SELECT statement to retrieve records from the database via a SELECT
command. To execute a SELECT statement you must:
The results of the SQL statement are retrieved into an EDBDataReader object.
5. Loops through the contents of the EDBDataReader object to display the records
returned by the query within a WHILE loop.
The Read() method advances to the next record (if a record exists) and returns true if a
record exists, or false to indicate that the EDBDataReader has reached the end of the
result set.
try
{
conn.Open();
EDBCommand cmdSelect = new EDBCommand("SELECT * FROM dept",conn);
cmdSelect.CommandType = CommandType.Text;
while(drDept.Read())
{
Response.Write("Department Number: " + drDept["deptno"]);
Response.Write("\tDepartment Name: " + drDept["dname"]);
Response.Write("\tDepartment Location: " + drDept["loc"]);
Response.Write("<br>");
}
catch(Exception exp)
{
Response.Write(exp.ToString());
}
finally
{
conn.Close();
}
}
</script>
To exercise the sample code, save the code in your default web root directory in a file
named:
selectEmployees.aspx
http://localhost/selectEmployees.aspx.
To retrieve a single result from a query, use the ExecuteScalar() method of the
EDBCommand object. The ExecuteScalar() method returns the first value of the first
column of the first row of the DataSet generated by the specified query.
cmd.CommandType = CommandType.Text;
}
catch(Exception exp)
{
Response.Write(exp.ToString());
}
finally
{
conn.Close();
}
}
</script>
selectscalar.aspx
http://localhost/selectScalar.aspx
Please note that the sample includes an explicit conversion of the value returned by the
ExecuteScalar() method. The ExecuteScalar() method returns an object; to view
the object, you must convert it into an integer value by using the Convert.ToInt32
method.
Parameterized queries are useful when you don't know the complete text of a query at the
time you write your code. For example, the value referenced in a WHERE clause may be
calculated from user input.
As demonstrated in the following example, you must declare the data type of each
parameter specified in the parameterized query by creating an EDBParameter object and
adding that object to the command's parameter collection. Then, you must specify a
value for each parameter by calling the parameter's Value() function.
The example demonstrates use of a parameterized query with an UPDATE statement that
increases an employee salary:
string updateQuery = "UPDATE emp SET sal = sal+500 where empno = :ID";
try {
conn.Open();
cmdUpdate.Parameters.Add
(new EDBParameter(":ID", EDBTypes.EDBDbType.Integer));
cmdUpdate.Parameters[0].Value = 7788;
cmdUpdate.ExecuteNonQuery();
Response.Write("Record Updated");
}
catch(Exception exp) {
Response.Write(exp.ToString());
}
finally {
conn.Close();
}
}
</script>
updateSalary.aspx
http://localhost/updateSalary.aspx
In the example that follows, the INSERT command is stored in the variable cmd. The
values prefixed with a colon (:) are placeholders for EDBParameters that are
instantiated, assigned values, and then added to the INSERT command's parameter
collection in the statements that follow. The INSERT command is executed by the
ExecuteNonQuery() method of the cmdInsert object.
try
{
conn.Open();
cmdInsert.Parameters.Add(new EDBParameter(":EmpNo",
EDBTypes.EDBDbType.Integer));
cmdInsert.Parameters[0].Value = 1234;
cmdInsert.Parameters.Add(new EDBParameter(":EName",
EDBTypes.EDBDbType.Text));
cmdInsert.Parameters[1].Value = "Lola";
cmdInsert.ExecuteNonQuery();
Response.Write("Record inserted successfully");
}
catch(Exception exp)
{
Response.Write(exp.ToString());
}
finally
{
conn.Close();
}
}
</script>
insertEmployee.aspx
http://localhost/insertEmployee.aspx
You can use the ExecuteNonQuery() method of EDBCommand to delete records from a
database stored on an Advanced Server host with a DELETE statement.
In the example that follows, the DELETE command is stored in the variable
strDeleteQuery. The code passes the employee number to the Delete command
(specified by :EmpNo). The command is then executed using the ExecuteNonQuery()
method. The following example deletes the employee inserted in the previous example:
try
{
conn.Open();
deleteCommand.Parameters.Add
(new EDBParameter(":ID", EDBTypes.EDBDbType.Integer));
deleteCommand.Parameters[0].Value = 1234;
deleteCommand.ExecuteNonQuery();
Response.Write("Record Deleted");
catch(Exception exp)
{
Response.Write(exp.ToString());
finally
{
conn.Close();
}
</script>
deleteEmployee.aspx
http://localhost/deleteEmployee.aspx
By packaging the SQL statements in a stored procedure, and executing the stored
procedure from the .NET application.
In some cases, a stored procedure can provide advantages over embedded SQL
statements. Stored procedures support complex conditional and looping constructs that
are difficult to duplicate with SQL statements embedded directly in an application.
You can also see a significant improvement in performance by using stored procedures; a
stored procedure only needs to be parsed, compiled and optimized once on the server
side, while a SQL statement that is included in an application may be parsed, compiled
and optimized each time it is executed from a .NET application.
3. Pass the name of the stored procedure to the instance of the EDBCommand.
Our sample procedure prints the name of department 10; the procedure takes no
parameters, and returns no parameters. To create the sample procedure, invoke EDB-
PSQL and connect to the Advanced Server host database. Enter the following SPL code
at the command line:
When Advanced Server has validated the stored procedure it will echo CREATE
PROCEDURE.
The CommandType property of the EDBCommand object is used to indicate the type of
command being executed. The CommandType property is set to one of three possible
CommandType enumeration values:
Use the default Text value when passing a SQL string for execution.
Use the StoredProcedure value, passing the name of a stored procedure for
execution.
Use the TableDirect value when passing a table name. This value passes back
all records in the specified table.
The CommandText property must contain a SQL string, stored procedure name, or table
name depending on the value of the CommandType property.
try
{
conn.Open();
cmdStoredProc.Prepare();
cmdStoredProc.ExecuteNonQuery();
}
catch(Exception exp)
{
Response.Write(exp.ToString());
}
finally
{
conn.Close();
}
}
</script>
storedProc.aspx
http://localhost/storedProc.aspx
OPEN TESTCUR;
FETCH TESTCUR INTO MAX_EMPNO;
INSERT INTO EMP(EMPNO,ENAME,JOB,SAL,COMM,DEPTNO,MGR)
VALUES(MAX_EMPNO+1,pENAME,pJOB,pSAL,pCOMM,pDEPTNO,pMgr);
CLOSE testcur;
END;
When Advanced Server has validated the stored procedure it will echo CREATE
PROCEDURE.
Calling a stored procedure that contains parameters is very similar to executing a stored
procedure without parameters. The major difference is that when calling a parameterized
stored procedure you must use the EDBParameter collection of the EDBCommand object.
When the EDBParameter is added to the EDBCommand collection, properties such as
ParameterName, DbType, Direction, Size, and Value are set.
try
{
conn.Open();
cmdStoredProc.Parameters.Add(new EDBParameter
("EmpName", EDBTypes.EDBDbType.Varchar));
cmdStoredProc.Parameters[0].Value = empName;
cmdStoredProc.Parameters.Add(new EDBParameter
("Job", EDBTypes.EDBDbType.Varchar));
cmdStoredProc.Parameters[1].Value = empJob;
cmdStoredProc.Parameters.Add(new EDBParameter
("Salary", EDBTypes.EDBDbType.Float));
cmdStoredProc.Parameters[2].Value = salary;
cmdStoredProc.Parameters.Add(new EDBParameter
("Commission", EDBTypes.EDBDbType.Float));
cmdStoredProc.Parameters[3].Value = commission;
cmdStoredProc.Parameters.Add(new EDBParameter
("DeptNo", EDBTypes.EDBDbType.Integer));
cmdStoredProc.Parameters[4].Value = deptno;
cmdStoredProc.Parameters.Add
(new EDBParameter("Manager", EDBTypes.EDBDbType.Integer));
cmdStoredProc.Parameters[5].Value = manager;
cmdStoredProc.Prepare();
cmdStoredProc.ExecuteNonQuery();
Response.Write(empInfo);
catch(Exception exp)
{
Response.Write(exp.ToString());
}
finally
{
conn.Close();
}
}
</script>
</script>
storedProcInParam.aspx
http://localhost/storedProcInParam.aspx
In the example, the body of the Page_Load method declares and instantiates an
EDBConnection object. The sample then creates an EDBCommand object with the
properties needed to execute the stored procedure.
The example then uses the Add method of the EDBCommand Parameter collection to
add six input parameters.
It assigns a value to each parameter before passing them to the EMP_INSERT stored
procedure
The previous example demonstrated how to pass IN parameters to a stored procedure; the
following examples demonstrate how to pass IN values and return OUT values from a
stored procedure.
The following stored procedure passes the department number, and returns the
corresponding location and department name. To create the sample procedure, open the
EDB-PSQL command line, and connect to the Advanced Server host database. Enter the
following SPL code at the command line:
OPEN TESTCUR;
FETCH TESTCUR INTO REC;
pDNAME := REC.DNAME;
pLOC := REC.LOC;
CLOSE testcur;
END;
When Advanced Server has validated the stored procedure it will echo CREATE
PROCEDURE.
When retrieving values from OUT parameters you must explicitly specify the direction of
out parameters as Output. You can retrieve the values from Output parameters in two
ways:
Call the ExecuteNonQuery method of EDBCommand and explicitly get the value
of a declared Output parameter by calling that EDBParameter value property.
In each method, you must declare each parameter, indicating the direction of the
parameter (ParameterDirection.Input, ParameterDirection.Output or
ParameterDirection.InputOutput). Before invoking the procedure, you must
provide a value for each IN and INOUT parameter. After the procedure returns, you may
retrieve the OUT and INOUT parameter values from the command.Parameters[] array.
The following code listing demonstrates using the ExecuteReader method to retrieve a
result set:
try
{
conn.Open();
EDBCommand command = new EDBCommand("DEPT_SELECT
(:pDEPTNO,:pDNAME,:pLOC)", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new EDBParameter("pDEPTNO",
EDBTypes.EDBDbType.Integer,10,"pDEPTNO",
ParameterDirection.Input,false ,2,2,
System.Data.DataRowVersion.Current,1));
command.Parameters.Add(new EDBParameter("pDNAME",
EDBTypes.EDBDbType.Varchar,10,"pDNAME",
ParameterDirection.Output,false ,2,2,
System.Data.DataRowVersion.Current,1));
command.Parameters.Add(new EDBParameter("pLOC",
EDBTypes.EDBDbType.Varchar,10,"pLOC",
ParameterDirection.Output,false ,2,2,
System.Data.DataRowVersion.Current,1));
command.Prepare();
command.Parameters[0].Value = 10;
EDBDataReader result = command.ExecuteReader();
int fc = result.FieldCount;
while(result.Read())
{
for(int i = 0;i < fc; i++)
{
Response.Write("RESULT["+i+"]="+ Convert.ToString
(command.Parameters[i].Value));
Response.Write("<br>");
}
}
catch(EDBException exp)
{
Response.Write(exp.ToString());
}
finally
{
conn.Close();
}
}
</script>
try
{
conn.Open();
EDBCommand command = new EDBCommand("DEPT_SELECT
(:pDEPTNO,:pDNAME,:pLOC)", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new EDBParameter("pDEPTNO",
EDBTypes.EDBDbType.Integer,10,"pDEPTNO",
ParameterDirection.Input,false ,2,2,
System.Data.DataRowVersion.Current,1));
command.Parameters.Add(new EDBParameter("pDNAME",
EDBTypes.EDBDbType.Varchar,10,"pDNAME",
ParameterDirection.Output,false ,2,2,
System.Data.DataRowVersion.Current,1));
command.Parameters.Add(new EDBParameter("pLOC",
EDBTypes.EDBDbType.Varchar,10,"pLOC",
ParameterDirection.Output,false ,2,2,
System.Data.DataRowVersion.Current,1));
command.Prepare();
command.Parameters[0].Value = 10;
command.ExecuteNonQuery();
Response.Write(command.Parameters["pDNAME"].Value.ToString());
Response.Write(command.Parameters["pLOC"].Value.ToString());
}
catch(EDBException exp)
{
Response.Write(exp.ToString());
}
finally
{
conn.Close();
}
}
</script>
Use the SYS_REFCURSOR built-in data type to declare a weakly-typed ref cursor.
Define a strongly-typed ref cursor that declares a variable of that type.
SYS_REFCURSOR is a ref cursor type that allows any result set to be associated with it.
This is known as a weakly-typed ref cursor. The following example is a declaration of a
weakly-typed ref cursor:
name SYS_REFCURSOR;
To use the above defined procedure from .NET code, you must specify the data type of
the ref cursor being passed as an IN parameter, as shown in the above script.
The following C# code uses the stored procedure to retrieve employee names from the
emp table:
using System;
using System.Data;
using EnterpriseDB.EDBClient;
using System.Configuration;
namespace EDBRefCursor
{
class EmpRefcursor
{
[STAThread]
static void Main(string[] args)
{
string strConnectionString =
ConfigurationSettings.AppSettings["DB_CONN_STRING"];
EDBConnection conn = new EDBConnection(strConnectionString);
conn.Open();
EDBTransaction tran = conn.BeginTransaction();
try
{
EDBTransaction tran = conn.BeginTransaction();
EDBCommand command = new EDBCommand("refcur_inout_callee",
conn);
command.CommandType = CommandType.StoredProcedure;
command.Transaction = tran;
command.Parameters.Add(new EDBParameter("refCursor",
EDBTypes.EDBDbType.Refcursor, 10, "refCursor",
ParameterDirection.InputOutput, false, 2, 2,
System.Data.DataRowVersion.Current, null));
command.Prepare();
command.Parameters[0].Value = null;
command.ExecuteNonQuery();
String cursorName = command.Parameters[0].Value.ToString();
command.CommandText = "fetch all in \"" + cursorName + "\"";
command.CommandType = CommandType.Text;
EDBDataReader reader =
command.ExecuteReader(CommandBehavior.SequentialAccess);
int fc = reader.FieldCount;
while (reader.Read())
{
for (int i = 0; i < fc; i++)
{
Console.WriteLine(reader.GetString(i));
}
}
reader.Close();
tran.Commit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
}
}
The following .NET code snippet displays the result on the console:
Please note that you must bind the EDBDbType.RefCursor type in EDBParameter()
if you are using a ref cursor parameter.
GeoJSON
Json.NET
Legacy PostGIS
NetTopologySuite
NodaTime
Rawpostgis
The plugins support the use of spatial, data/time and Json types. The following sections
detail the supported frameworks and data provider installation path for these plugins.
5.8.1 GeoJSON
If you are using the GeoJSON plugin on .NET Framework 4.5, the data provider
installation path is:
C:\Program Files\edb\dotnet\plugins\GeoJSON\net45
EnterpriseDB.EDBClient.GeoJSON.dll
GeoJSON.Net.dll
Newtonsoft.Json.dll
If you are using the GeoJSON plugin on .NET Standard 2.0, the data provider installation
path is:
C:\Program Files\edb\dotnet\plugins\GeoJSON\netstandard2.0
EnterpriseDB.EDBClient.GeoJSON.dll
For detailed information about using the GeoJSON plugin, see the Npgsql documentation
available at:
http://www.npgsql.org/doc/types/geojson.html
5.8.2 Json.NET
If you are using the Json.NET plugin on .NET Framework 4.5, the data provider
installation path is:
C:\Program Files\edb\dotnet\plugins\Json.NET\net45
EnterpriseDB.EDBClient.Json.NET.dll
Newtonsoft.Json.dll
If you are using the Json.NET plugin on .NET Standard 2.0, the data provider installation
path is:
C:\Program Files\edb\dotnet\plugins\Json.NET\netstandard2.0
EnterpriseDB.EDBClient.Json.NET.dll
For detailed information about using the Json.NET plugin, see the Npgsql documentation
available at:
http://www.npgsql.org/doc/types/jsonnet.html
5.8.3 LegacyPostGIS
If you are using the LegacyPostGIS plugin on .Net Framework 4.5, the data provider
installation path is:
C:\Program Files\edb\dotnet\plugins\LegacyPostgis\net45
EnterpriseDB.EDBClient.LegacyPostgis.dll
If you are using the LegacyPostGIS plugin on .Net Standard 2.0, the data provider
installation path is:
C:\Program
Files\edb\dotnet\plugins\LegacyPostgis\netstandard2.0
EnterpriseDB.EDBClient.LegacyPostgis.dll
For detailed information about using the LegacyPostGIS plugin, see the Npgsql
documentation available at:
http://www.npgsql.org/doc/types/legacy-postgis.html
5.8.4 NetTopologySuite
If you are using the NetTopologySuite plugin on .Net Framework 4.5, the data provider
installation path is:
EnterpriseDB.EDBClient.NetTopologySuite.dll
GeoAPI.dll
NetTopologySuite.dll
NetTopologySuite.IO.PostGis.dll
If you are using the NetTopologySuite plugin on .Net Standard 2.0, the data provider
installation path is:
C:\Program
Files\edb\dotnet\plugins\NetTopologySuite\netstandard2.0
EnterpriseDB.EDBClient.NetTopologySuite.dll
For detailed information about using the NetTopologySuite type plugin, see the Npgsql
documentation available at:
http://www.npgsql.org/doc/types/nts.html
5.8.5 NodaTime
If you are using the NodaTime plugin on .Net Framework 4.5, the data provider
installation path is:
C:\Program Files\edb\dotnet\plugins\NodaTime\net45
EnterpriseDB.EDBClient.NodaTime.dll
NodaTime.dll
If you are using the NodaTime plugin on .Net Standard 2.0, the data provider installation
path is:
C:\Program Files\edb\dotnet\plugins\NodaTime\netstandard2.0
EnterpriseDB.EDBClient.NodaTime.dll
For detailed information about using the NodaTime plugin, see the Npgsql
documentation available at:
http://www.npgsql.org/doc/types/nodatime.html
5.8.6 RawPostGIS
If you are using the RawPostGIS plugin on .Net Framework 4.5, the data provider
installation path is:
C:\Program Files\edb\dotnet\plugins\RawPostgis\net45
EnterpriseDB.EDBClient.RawPostgis.dll
If you are using the RawPostGIS type plugin on .Net Standard 2.0, the data provider
installation path is:
C:\Program\Files\edb\dotnet\plugins\RawPostGis\netstandard2.0
EnterpriseDB.EDBClient.RawPostgis.dll
For detailed information about using the RawPostGIS plugin, see the documentation
available at:
https://www.nuget.org/packages/Npgsql.RawPostgis/
http://www.npgsql.org/doc/api/Npgsql.html
Usage notes: