PostgreSQL C#: Creating Tables
Summary: in this tutorial, you will learn how to create new tables in the PostgreSQL database from a C# program.
This tutorial begins where the Connecting to the PostgreSQL database from a C# program tutorial left off.
How to create tables in PostgreSQL using C#
To create a new table in a PostgreSQL database from a C# program, you follow these steps:
First, construct a CREATE TABLE
statement:
Second, open a connection to the PostgreSQL database:
Third, create a NpgsqlCommand
object:
Fourth, execute the CREATE TABLE
statement by calling the ExecuteNonQueryAsync()
method of the command object:
Finally, close the database connection. Note that the using
statement automatically closes the database connection when it goes out of scope.
Creating new tables
The following program illustrates how to create three tables courses
, students
, and enrollments
in the elearning
database:
How it works.
First, construct a list of CREATE
TABLE
statements:
Next, get the connection string using the ConfigurationHelper
class:
Then, create a new data source from the connection string:
After that, iterate over the statements list and execute each statement by calling the ExecuteNonQueryAsync()
method:
Finally, use the try-catch statement to catch any exceptions that may occur and display the error message:
Verify table creation
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, run the \dt
command to show all tables in the elearning
database:
Output:
The output indicates that the program has successfully created three tables including courses
, enrollments
, and students
.
Summary
- Call the
ExecuteNonQueryAsync()
method of theNpgsqlCommand
to execute aCREATE
TABLE
statement to create a new table in the PostgreSQL database.