Using PostgreSQL in .NET

Introduction

 
PostgreSQL is one of the most important relational database systems in the open-source world. It is released under a BSD style license. I've seen a few documents talking about the development of a .NET application with PostgreSQL as the back-end server. That's why I'm writing this article to illustrate how you can access the PostgreSQL database system using C#.
 

Getting started with the solution

 
For this solution, we're going to use the PostgreSQL database system which can be downloaded from http://www.postgresql.org/.  You can also find good documentation on this site. For the creation of the database and its underlying schema, we're going to use pgAdmin III. In order to access the PostgreSQL database system from Microsoft.NET, we're going to use the NpgSQL2 driver for ADO.NET which can be downloaded from http://npgsql.projects.postgresql.org/.  When you unzip the npgsql archive, you can find the driver in the Npgsql.dll library inside the bin directory.
 
Now let's open the pgAdmin III management console and create a connection to the PostgreSQL database system (see Figure 1).
 
1.gif
 
Figure 1
 
Next step is to create a test database (see Figure 2).
 
2.gif
 
Figure 2
 
Then open the Query editor to execute the SQL statement for the creation of the database objects by clicking on the 3.gif icon on the pgAdmin III toolbar.
 
Next step is to create a table to store information about the employee of the company (see Listing 1).
  1. CREATE TABLE emp  
  2. (  
  3. empno integer NOT NULL,  
  4. empname varchar(50),  
  5. salary numeric(6,2),  
  6. CONSTRAINT emp_pkey PRIMARY KEY (empno)  
  7. )  
  8. WITH (OIDS=FALSE);  
  9. ALTER TABLE emp OWNER TO john;  
Listing 1
 
Now let's add some data to the emp table (see Listing 2).
  1. INSERT INTO emp (empno, empname, salary) VALUES (1, 'John', 3400.99);  
  2. INSERT INTO emp (empno, empname, salary) VALUES (2, 'Mary', 2400.55);  
  3. INSERT INTO emp (empno, empname, salary) VALUES (3, 'Peter', 1900.99);  
Listing 2
 
Now let's open the Visual Studio.NET 2008, and create a Windows Forms Application project (see Figure 3).
 
4.gif
 
Figure 3
 
The first step of the Windows Forms application is to add a reference to the Npgsql.dll assembly as shown in Figure 4.
 
5.gif
 
Figure 4
 
Let's add a dataset to define the schema of the business entities holding the data related to the employees (see Figure 5).
 
6.gif
 
Figure 5
 
Then right-click on the strongly typed Data Set and add a data table (see Figure 6).
 
7.gif
 
Figure 6
 
Then define the fields of the Employee data table matching the columns of the employee table in PostgreSQL (see Figure 7).
 
8.gif
 
Figure 7
 
Now let's bind the Employee business entity and its fields to the main windows form by opening the Data Sources windows and dragging and dropping the Employee node onto the form in Details mode.
 
Some binding artifacts are automatically created such as an instance of the strongly typed Data Set named dsHumanResources, an instance of the BindingSource class, and another instance of the BindingNavigator class.
 
The last part of the application is the code to access the back-end database server and to display the data on the form.
The data load code is implemented in the Form_Load event handler of the windows form (see Listing 3).
  1. private void Form1_Load(object sender, EventArgs e)  
  2. {  
  3.     string strConnString = "Server=remote_server;Port=5432;User Id=john;Password=john;Database=test";  
  4.     try  
  5.     {  
  6.         NpgsqlConnection objConn = new NpgsqlConnection(strConnString);  
  7.         objConn.Open();  
  8.         string strSelectCmd = "select empno, empname, salary from emp";  
  9.         NpgsqlDataAdapter objDataAdapter = new NpgsqlDataAdapter(strSelectCmd, objConn);  
  10.         objDataAdapter.Fill(this.dSHumanResources.Employee);  
  11.         objConn.Close();  
  12.     }  
  13.     catch (Exception ex)  
  14.     {  
  15.         System.Windows.Forms.MessageBox.Show(ex.Message,"Error message",MessageBoxButtons.OK, MessageBoxIcon.Error);  
  16.     }  
  17. }   
Listing 3
 
Now let's implement the logic to commit the changes on the client data set by coding the event handler of the click event on a new button on the form (see Listing 4).
  1. private void button1_Click(object sender, EventArgs e)  
  2. {  
  3.     this.employeeBindingSource.EndEdit();  
  4.    
  5.     string strConnString = "Server=remote_server;Port=5432;User Id=john;Password=john;Database=test";  
  6.     try  
  7.     {  
  8.         NpgsqlConnection objConn = new NpgsqlConnection(strConnString);  
  9.         objConn.Open();  
  10.         string strUpdateCmd = "update emp set empname=:empname, salary=:salary where empno=:empno";  
  11.         NpgsqlParameter objParameter = null;  
  12.         NpgsqlCommand objUpdateCmd = new NpgsqlCommand(strUpdateCmd, objConn);  
  13.         objParameter = objUpdateCmd.Parameters.Add(":empno", NpgsqlTypes.NpgsqlDbType.Integer);  
  14.         objParameter.SourceColumn = "empno";  
  15.         objParameter.SourceVersion = DataRowVersion.Original;  
  16.         objParameter = objUpdateCmd.Parameters.Add(":empname", NpgsqlTypes.NpgsqlDbType.Varchar, 50);  
  17.         objParameter.SourceColumn = "empname";  
  18.         objParameter.SourceVersion = DataRowVersion.Current;  
  19.         objParameter = objUpdateCmd.Parameters.Add(":salary", NpgsqlTypes.NpgsqlDbType.Numeric);  
  20.         objParameter.SourceColumn = "salary";  
  21.         objParameter.SourceVersion = DataRowVersion.Current;  
  22.         NpgsqlDataAdapter objDataAdapter = new NpgsqlDataAdapter();  
  23.         objDataAdapter.UpdateCommand = objUpdateCmd;  
  24.         objDataAdapter.Update(this.dSHumanResources.Employee);  
  25.         objConn.Close();  
  26.     }  
  27.     catch (Exception ex)  
  28.     {  
  29.         System.Windows.Forms.MessageBox.Show(ex.Message, "Error message", MessageBoxButtons.OK, MessageBoxIcon.Error);  
  30.     }  
  31. }  
Listing 4
 

Conclusion

In this article, I've illustrated how to access a PostgreSQL database using C# and Microsoft.NET framework.


Similar Articles