PostgreSQL C#: Updating Data
Summary: in this tutorial, you will learn how to update data in the PostgreSQL database using C#.
This tutorial begins where importing data from a CSV file into PostgreSQL tutorial is left off.
How to update data in PostgreSQL using C#
To update a row from a table in a PostgreSQL database from a C# program, you follow these steps:
First, construct an UPDATE
statement:
In the UPDATE
statement, you can add parameters in the format @parameter
. When you execute the query, you need to bind values to these parameters.
Using the parameters in the query helps you to prevent SQL injection attacks when the values come from untrusted sources such as user inputs.
Second, create a data source that represents the PostgreSQL database:
Third, create a NpgsqlCommand
object and bind one or more values to the parameters:
Finally, execute the UPDATE
statement by calling the ExecuteNonQueryAsync()
method of the command object:
Note that the using
statement will automatically close the database connection when it is not used.
Updating data in a table
The following C# program modifies the email of the row with id 1 in the students
table in the elearning
database:
How it works.
First, construct an UPDATE statement that inserts a new row into the students
table:
These @email
and @id
are the placeholders for parameters in the UPDATE
command.
Second, get the connection string from the configuration using the ConfigurationHelper
class:
Third, create a data source that represents the PostgreSQL database:
Fourth, create a new NpgsqlCommand
object and bind the values to its parameters:
Fifth, execute the UPDATE
statement by calling the ExecuteNonQueryAsync()
method and display a success message:
Finally, display an error message if any exceptions occur during the update:
Verify the update
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.
Second, query data from the students
table:
Output:
The output indicates that the program has successfully updated the email of row id 1 to [[email protected]](../cdn-cgi/l/email-protection.html)
.
Summary
- Use the
NpgsqlCommand
object to execute anUPDATE
statement that updates a row into a table.