Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » .NET 3.0/3.5 » Using PostgreSQL from Microsoft.NET

Using PostgreSQL from Microsoft.NET

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 .NET application with PostgreSQL as the back-end server. That’s why I’m writing this article to illustrate how you can access to the PostgreSQL database system using C#.

Author Rank:
Total page views :  2943
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor


MindCracker Survey


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 .NET application with PostgreSQL as the back-end server. That's why I'm writing this article to illustrate how you can access to 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 a good documentation in this site. For the creation of the database and its underlying schema, we're going to use pgAdmin III. In order to access to the PostgreSQL database system from Microsoft.NET, we're going to use 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.gificon on the pgAdmin III toolbar.

Next step is to create a table to store information about the employee of the company (see Listing 1).

CREATE TABLE emp
(
empno integer NOT NULL,
empname varchar(50),
salary numeric(6,2),
CONSTRAINT emp_pkey PRIMARY KEY (empno)
)
WITH (OIDS=FALSE);
ALTER TABLE emp OWNER TO john;

Listing 1

Now let's add some data to the emp table (see Listing 2).

INSERT INTO emp (empno, empname, salary) VALUES (1, 'John', 3400.99);
INSERT INTO emp (empno, empname, salary) VALUES (2, 'Mary', 2400.55);
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 the 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 to 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).

private void Form1_Load(object sender, EventArgs e)
{
    string strConnString = "Server=remote_server;Port=5432;User Id=john;Password=john;Database=test";
    try
    {
        NpgsqlConnection objConn = new NpgsqlConnection(strConnString);
        objConn.Open();
        string strSelectCmd = "select empno, empname, salary from emp";
        NpgsqlDataAdapter objDataAdapter = new NpgsqlDataAdapter(strSelectCmd, objConn);
        objDataAdapter.Fill(this.dSHumanResources.Employee);
        objConn.Close();
    }
    catch (Exception ex)
    {
        System.Windows.Forms.MessageBox.Show(ex.Message,"Error message",MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

}

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).

private void button1_Click(object sender, EventArgs e)
{
    this.employeeBindingSource.EndEdit();
 
    string strConnString = "Server=remote_server;Port=5432;User Id=john;Password=john;Database=test";
    try
    {
        NpgsqlConnection objConn = new NpgsqlConnection(strConnString);
        objConn.Open();

        string strUpdateCmd = "update emp set empname=:empname, salary=:salary where empno=:empno";
        NpgsqlParameter objParameter = null;
        NpgsqlCommand objUpdateCmd = new NpgsqlCommand(strUpdateCmd, objConn);
        objParameter = objUpdateCmd.Parameters.Add(":empno", NpgsqlTypes.NpgsqlDbType.Integer);
        objParameter.SourceColumn = "empno";
        objParameter.SourceVersion = DataRowVersion.Original;
        objParameter = objUpdateCmd.Parameters.Add(":empname", NpgsqlTypes.NpgsqlDbType.Varchar, 50);
        objParameter.SourceColumn = "empname";
        objParameter.SourceVersion = DataRowVersion.Current;
        objParameter = objUpdateCmd.Parameters.Add(":salary", NpgsqlTypes.NpgsqlDbType.Numeric);
        objParameter.SourceColumn = "salary";
        objParameter.SourceVersion = DataRowVersion.Current;

        NpgsqlDataAdapter objDataAdapter = new NpgsqlDataAdapter();
        objDataAdapter.UpdateCommand = objUpdateCmd;
        objDataAdapter.Update(this.dSHumanResources.Employee);
        objConn.Close();
    }
    catch (Exception ex)
    {
        System.Windows.Forms.MessageBox.Show(ex.Message, "Error message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

Listing 4

Conclusion

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


Login to add your contents and source code to this article
 About the author
 
John Charles Olamendy
He’s a senior Integration Solutions Architect and Consultant. His primary area of involvement is in Object-Oriented Analysis and Design, Database design , Enterprise Application Integration, Unified Modeling Language, Design Patterns and Software Development Process. He has knowledge and extensive experience in the development of Enterprise Applications using Microsoft.NET and J2EE technologies and standards. He is proficient with distributed systems programming; and business-process integration and messaging using the principles of the Services Oriented Architecture (SOA) and related technologies such as Microsoft BizTalk Server, Web Services (Windows Communication Foundation, WSE, BEA WebLogic, Oracle AS and Axis) through multiple implementations of loosely-coupled system. He’s a prolific blogger contributing to .NET and J2EE communities and actively writes articles on subjects relating to integration of applications, business intelligence, and enterprise applications development. He holds a Master’s degree in Business Informatics at Otto Von Guericke University, Magdeburg, Germany. He was recently awarded as MVP. He currently works in the telecommunication industry and delivers integration solutions for this industry. He harbors a true passion for the technology.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
good article by Mohammed On August 20, 2009
Well done
A simple tutorial build a great base of "How to start postgreSQL"

Mohammed Thabet Zaky
SW Developer
Cairo,Egypt
http://www.thabettech.blogspot.com/

Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2010  Mindcracker LLC. All Rights Reserved