PostgreSQL C#: Call a Stored Procedure
Summary: in this tutorial, you will learn to call a PostgreSQL stored procedure from a C# program using ADO.NET
How to call a PostgreSQL stored procedure in C#
The following are the steps for calling a PostgreSQL stored procedure in C#:
First, create a data source that represents the PostgreSQL database:
Second, create a new NpgsqlCommand
object from the statement that calls a stored procedure:
The $1
and $2
are placeholders for binding parameters to the stored procedure.
Third, optionally, bind values to the command:
Fourth, execute the stored procedure call by calling the ExecuteNonQueryAsync()
method of the NpgsqlCommand
object:
We’ll create a new stored procedure in the PostgreSQL server and call it from a C# program.
Creating a PostgreSQL stored procedure
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 PostgreSQL stored procedure that enrolls a student and creates an invoice:
Calling the PostgreSQL stored procedure in C#
The following C# program invokes the enroll_student
stored procedure from the PostgreSQL database:
How it works.
First, declare and initialize variables for storing the enrollment details including studentId
, courseId
, amount
, tax
, and invoiceDate
:
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 call to the enroll_student
stored procedure:
Note that $1
, $2
, $3
, $4
and $5
are the parameter placeholders you need to bind values when executing the command.
Fifth, bind the variables to the parameters of the NpgsqlCommand
object:
Sixth, execute the command that calls the PostgreSQL stored procedure:
Finally, show the error message if any exceptions occur:
Verify the stored procedure call
First, connect to the elearning
database using the ed
user:
Second, retrieve data from the enrollments table:
Output:
Third, retrieve data from the invoices table:
Output:
The output shows that the program successfully called the stored procedure enroll_student
that inserts new rows into the enrollments
and invoices
tables;
Summary
- Call the
ExecuteNonQueryAsync()
method of theNpgsqlCommand
object to execute a call to a PostgreSQL stored procedure from a C# program.