PostgreSQL C#: Call a PostgreSQL Function
Summary: in this tutorial, you will learn to call a PostgreSQL function from a C# program using ADO.NET
How to call a PostgreSQL function in C#
Here are the steps for calling a PostgreSQL function in C#:
First, create a data source that represents the PostgreSQL database:
Second, create a new NpgsqlCommand
object from the statement that calls a PostgreSQL function:
Third, optionally, bind values to the query’s parameters:
Fourth, execute the function call by calling the ExecuteReaderAsync()
method of the NpgsqlCommand
object:
The ExecuteReaderAsync()
returns a NpgsqlDataReader
object.
Finally, read the return values of the function by calling the ReadAsync()
method of the NpgsqlDataReader
object:
We’ll create a new function in the PostgreSQL server and call it from a C# program.
Creating a PostgreSQL function
First, open a terminal and connect to the elearning
database using the ed
user:
It’ll prompt you to enter a password for the ed
user. Input the valid password and press Enter to connect to the PostgreSQL server.
Second, create a stored procedure in PostgreSQL, which enrolls a student in a course and creates a corresponding invoice:
Calling the PostgreSQL function in C#
The following C# program invokes the `enroll_student_and_create_invoice` function from the PostgreSQL database:
How it works.
First, declare and initialize variables beginDate
and endDate
to May 10 2024 and May 15 2024:
Second, get the connection string from the configuration file using the ConfigurationHelper
class:
Third, create a data source that represents the PostgreSQL database:
Fourth, create a new NpgsqlCommand
object that will execute a function call to the get_student_count()
function:
Notice that $1
and $2
are the parameter placeholders you need to bind values when executing the command.
Fifth, bind the beginDate
and endDate
to the parameters of the NpgsqlCommand
object:
Sixth, execute the command function call:
Seventh, read the student count and display it in the console:
Finally, display the error message if any exceptions occur:
Summary
- Call the
ExecuteReaderAsync()
method of theNpgsqlCommand
object to execute a call to a PostgreSQL function from a C# program.