Summary: in this tutorial, you will learn how to insert data into a table in the PostgreSQL database from a C# program.
This tutorial begins where the Creating Tables in PostgreSQL database from a C# program tutorial left off.
How to insert data into PostgreSQL database using C#
To insert a new row into a table in a PostgreSQL database from a C# program, you follow these steps:
First, construct an INSERT
statement:
In the SQL statement, you can have one or more parameters in the format @parameter
. When you execute it, you can bind values to these parameters.
This allows you to prevent SQL injection attacks if the values come from untrusted sources such as form input.
Second, create a new data source from the connection string:
Third, create a NpgsqlCommand
object from the data source with the INSERT
statement:
Finally, execute the INSERT
statement by calling the ExecuteNonQueryAsync()
method of the command object:
The following C# program inserts a row into the students
table in the elearning
database:
How it works.
First, create a new record called Student
that includes the FirstName
, LastName
, Email
, and RegistrationDate
fields:
Second, define a new instance of the Student
record for insertion into the students
table:
Third, construct an INSERT
statement that inserts a new row into the students
table:
These @first_name
,@last_name
,@email
, and @registration_date
are placeholders for parameters in the SQL command.
Fourth, get the connection string and establish a connection to the PostgreSQL server:
Fifth, create a new NpgsqlCommand
object and bind the values to its parameters:
Sixth, execute the INSERT
statement by calling the ExecuteNonQueryAsync()
method:
Finally, display an error message if any exceptions occur during the insertion:
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 inserted a new row into the students
table.
- Use the
NpgsqlCommand
object to execute an INSERT
statement that inserts a row into a table.