Click here to Skip to main content
Click here to Skip to main content

Using PostgreSQL in your C# (.NET) application (An introduction)

By , 15 Nov 2008
 

Introduction

In this article, I would like to show you the basics of using a PostgreSQL database in your .NET application. The reason why I'm doing this is the lack of PostgreSQL articles on CodeProject despite the fact that it is a very good RDBMS. I have used PostgreSQL back in the days when PHP was my main programming language, and I thought.... well, why not use it in my C# application.

Background

I assume you have a basic knowledge of databases, SQL commands, and so on.

Why PostgreSQL

First and foremost, it's free*, in BSD-style freedom (both libre and gratis), which means you will not have license problems in your commercial applications. Next, you have a very good procedural language called PL/pgSQL (there are also the Java, Perl, Python, Tcl (and other) flavors). Lots of communities support it (large ones like Planet PostgreSQL, or blogs, for instance, "Depesz" blog), and finally, lot's of fun exploring this pearl of open source databases.

Installing PostgreSQL and the .NET data provider

First of all, go to the PostgreSQL website. PostgreSQL is known for having a very good documentation system. For the purposes of this article, I used PostgreSQL v.8.3.4 and PgAdmin III v. 1.8.4 (that comes bundled with PostgreSQL). Remember to install the database and PgAdmin III, but NOT Npgsql, since it comes with version 1.x and we're going to use v. 2.0. from a different package. Now, if you have a PostgreSQL server up and running (which is a really easy task), let's download some drivers. For this article, I have used NpgSQL2 built directly for MS .NET. When you download it, in the zip package (\bin directory), you will find Npgsql.dll, and that's the library we're looking for.

Playing with PgAdmin III

If you have ever worked with any DB-Management software like Aqua Data Studio, SQL Manager (I use the Lite version every day), or the MS Management Studio Express, you will find PgAdmin III really intuitive. It may not have that many gizmos as others, but it will do the job nicely. Here are a couple of daily tasks that you probably want to know how to do.

  1. Creating a new user (unless you really don't mind playing with a super-user account :-)):
  2. How to create new role on the server

  3. Creating a new database (fairly obvious, but nevertheless here it goes :-)):
  4. How to create new database in PgAdmin III

  5. Creating a table:
  6. How to create new table in PostgreSQL

  7. Adding stuff to tables (there are, of course, other ways, but I will let you explore this):
  8. How to add more tables

  9. If you are looking for an MS-SQL Identity, just make your column type serial, or look for sequence in the documentation. OK, to be completely honest, PgAdmin III still needs work... numbers may not appear if you add a row through the grid, but believe me, they are there :-). You will see them the next time you reload a window with the grid.
  10. If you looking for more hit documentation :-)

Making a database

Here is a SQL-script so we can make our test database. Remember to create a database and a user. My user for this article will be adrian.

CREATE TABLE simple_table
(
  id integer NOT NULL, -- SERIAL if like identity-like functionality
  tekst character varying(50),
  CONSTRAINT simple_table_pkey PRIMARY KEY (id)
)
WITH (OIDS=FALSE);
ALTER TABLE simple_table OWNER TO adrian; -- my user

-- i drop Polish letters so i don't have to worry about codepage
INSERT INTO simple_table (id, tekst) VALUES (1, 'jaki tekst');
INSERT INTO simple_table (id, tekst) VALUES (2, 'jaki inny tekst');
INSERT INTO simple_table (id, tekst) VALUES (3, 'jeszcze inny tekst');

Using PostgreSQL in C#

Just make an empty Windows Forms application, and add a reference to Npgsql.dll, like shown in the picture:

Adding Npgsql provider

Baking a connection string PostgreSQL-style

A connection string in PostgreSQL is made by making keyword=value; pairs (Important: even the last element must end with a ';'). The most basic ones are:

  • Server - specifies the server location
  • User Id - the database user
  • Port - default is 5432
  • Password - the password for the database user
  • Database - the database name

Simple test application

using Npgsql;

namespace PostgreSQLTEst
{
    public partial class Form1 : Form
    {
        private DataSet ds = new DataSet();
        private DataTable dt = new DataTable();
        public Form1()
        {    
            InitializeComponent();    
        }
        private void llOpenConnAndSelect_LinkClicked(object sender, 
                     LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                // PostgeSQL-style connection string
                string connstring = String.Format("Server={0};Port={1};" + 
                    "User Id={2};Password={3};Database={4};",
                    tbHost.Text, tbPort.Text, tbUser.Text, 
                    tbPass.Text, tbDataBaseName.Text );
                // Making connection with Npgsql provider
                NpgsqlConnection conn = new NpgsqlConnection(connstring);
                conn.Open();
                // quite complex sql statement
                string sql = "SELECT * FROM simple_table";
                // data adapter making request from our connection
                NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
                // i always reset DataSet before i do
                // something with it.... i don't know why :-)
                ds.Reset();
                // filling DataSet with result from NpgsqlDataAdapter
                da.Fill(ds);
                // since it C# DataSet can handle multiple tables, we will select first
                dt = ds.Tables[0];
                // connect grid to DataTable
                dataGridView1.DataSource = dt;
                // since we only showing the result we don't need connection anymore
                conn.Close();
            }
            catch (Exception msg)
            {
                // something went wrong, and you wanna know why
                MessageBox.Show(msg.ToString());
                throw;
            }
        }
    }
}

And the effect:

Working example

And, that's it! :D. Practice PostgreSQL and enjoy!

Final words

This article is for those who have used a database for a couple of months (or even years) and would like to taste something different. If you are looking for a solid, stable, secure, and relatively fast database - PostgreSQL is for you. It costs 0.00 $, it has some cool features (look into the documentation and you will find them), and it is free.

I hope that you enjoyed my article :-)

Really final words.... :-)

The project has two dependencies. The first is Npgsql.dll (provider) and the second is MultiCtrls (which is a DLL that was built in my other article). If something is wrong with the sources, please make references by hand (MultiCtrls is bundled with the ZIP file).

License

This article, along with any associated source code and files, is licensed under The BSD License

About the Author

Adrian Pasik
Software Developer AP-System
Poland Poland
Member
Born in Kielce, Poland in 1983
 
Back in the days i programmed C++ projects for pure fun. In 2000 i was administrator of one network with 128 kbit bandwidth to the internet. Since we couldnt afford Microsoft NT software for our server i dived into the fantastic world of FLOSS. I started interesting in security of computing and of course did some reasearch in that field. Later on i did few commercial projects in PHP and MySQL. Soon after that i drop MySQL in order to store my data in PostgreSQL. Did also few exec's of OpenGL + GLSL to know what my graphics card is capable of. Started C#( and generally went back to Windows programming) in early 2007 and feeling this trend will last for some time...
 
Since begining of 2010 i work as an independent contractor.
 
I specialize at C#, mostly in Win Forms. I have some knowledge of ASP.NET but so far i didnt have some exciting project in this technology.
 
Speaking of 3rd party components I have been with DevExpress and I recommend it, except of the productivity plugins which are in my humble opinion not so good, but You will find people that like them.
If You want good productivity plugin, use Jetbrains ReSharper.
 
I'm fan of TDD since early 2011.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionSending List to the postgres dbmemberMember 810061424 Apr '13 - 7:17 
Hi,thanks for the article.
here comes my situation.
If need to send a list of objects (in c#) to a stored procedure in postgres.
In c#, how do I have to write the SQL string
for example:
List myList;
String sql="SELECT FROM my_stored_procedure_that_process_list(mylist)";
 
And the other part of the question, what kind of object type in postgres should I use to receive that list.
 
CREATE FUNCTION my_stored_procedure_that_process_list(my_list ?????)
QuestionYour code doesn't work. please help me.memberJesus Christ's servant14 Apr '13 - 23:44 
I tried to use your source code of connecting c# and postgres but everytime I run the program it always look for mono.security.dll, how can I solved this problem?
I already add references the mono.security.dll but nothing happen.
Please help me, i need this for my project in my school.
Thank you.
GeneralMy vote of 5memberMember 876091425 Feb '13 - 0:18 
Easy to get really fast started.
QuestionI want to add setup of postgressql in my .net application setupmemberAarti Meswania24 Feb '13 - 18:28 
can I install postgres-sql silently with my .net app. setup?
please reply
QuestionCan't find the providermemberebeid1 Feb '13 - 4:54 
Hello,
 
Thanks for the wonderful article. I can't find the provider (their website is down and nobody is responding) and I need it for urgent project.
could you please send me the the provider to ebeid@ieee.org ?
 
Thanks,
Ebeid
Ebeid soliman

GeneralMy vote of 5memberPhlebass11 Sep '12 - 22:58 
Thanks, great article on getting going with C#/PostGres
QuestionNicememberAli Tavakoli25 Dec '11 - 3:49 
very good article
thnx
GeneralMy vote of 5memberdaylightdj12 Sep '11 - 7:49 
5 because I was able to read the article in 5 minutes and get the idea of what it would be like to implement PostgreSql in a C# (.NET) environment. thx
GeneralMy vote of 5memberv# guy2 Aug '11 - 17:50 
very useful, thanks.
GeneralMy vote of 5membertoghyani29 Jul '11 - 7:29 
thanks adrian.
GeneralMy vote of 5memberNaked-heart20 Apr '11 - 5:04 
Excellent! Fast, Simple, Free!
You solved a lot of problems for a noob like me!!
The few problems I encountred are related to the installation of the PostgreSQL under Win 7 Pro 64 bit.
Thank You!!!
GeneralMy vote of 5memberZanolini Luca1 Mar '11 - 4:07 
it's work and explain is so chep
GeneralMy vote of 5memberShahriar Iqbal Chowdhury24 Nov '10 - 9:26 
Nice explanation
GeneralMy vote of 4memberlepetitchu17 Oct '10 - 17:12 
clear
GeneralMy vote of 5memberJeromeOfSuburbia12 Oct '10 - 22:45 
working
GeneralMy vote of 4memberdienius4 Jul '10 - 23:56 
Simple, good for beginner
GeneralThank you [modified]memberalaindominique6 Jun '10 - 4:15 
Hello,
 
Simple to understand and useful.
Thank you
 
Alain

modified on Sunday, June 6, 2010 10:37 AM

GeneralConnect postgres using c#memberkjhg3 Dec '09 - 23:56 
I tried this example. But I couldn't connect to the database(postgres). Could you please tell me how can I make a connection using c#. I have c# code and DB separately. I'm new to .net and I have no idea :(
NewsPostgreSQL can support arabic fonts nowmemberThabet Tech24 May '09 - 5:32 
Hi all,
Thanks Adrian Pasik for this helpful post
I faced problem of enabling postgreSQL to arabic until I found a solution to it
Solution is at the following link
http://thabettech.blogspot.com/2009/05/postgresql-support-arabic.html[^]
GeneralFailed to establish a connection...memberRodrigo Castilho11 May '09 - 9:04 
First of all, this is a great article!
 
The topic is relevant, and the text is clear and objective. Thanks for posting it!
 
But for some reason, I keep getting a "Failed to establish a connection to 192.168.1.104" message...
 
I have a client software that needs to read some data from a PostgreSQL database accross a local network (installed in a machine with the IP address above). I followed exacatly your instructions, but I keep getting this message...
 
Any clues?
 
Thanks again,
 
Rodrigo.
QuestionImposible make "IsolationLevel.ReadUncommitted"memberDavidRRR11 Feb '09 - 11:22 
I was trying to create a 'IsolationLevel.ReadUncommitted' but gives me this error :
"isolation parameter name: Must be Read Committed or Serializable".
 
the code is like that:
 
	StringBuilder sbSQL;
	Npgsql.NpgsqlConnection Con = creaConexion();
	Npgsql.NpgsqlCommand Comm   = new Npgsql.NpgsqlCommand("::SQL CODE::",Con);
 
	Npgsql.NpgsqlTransaction Tran = null;  
					
	try
	{
		Con.Open();
 
		<* ERROR IN THIS LINE *>
		Tran = Con.BeginTransaction( IsolationLevel.ReadUncommitted ); 
			
                ... CODIGO SQL ...
 
		Tran.Commit();
	}
	catch (Exception Er)
	{
		Tran.Rollback();
	}
		finally
	{
		Con.Close();
		Con.Dispose();
		Comm.Dispose();
		Adap.Dispose();
		Tran.Dispose();
	}
 
pretty please HELP ME!
AnswerRe: Imposible make "IsolationLevel.ReadUncommitted"memberAdrian Pasik12 Feb '09 - 5:39 
take a look at npgsql forums/mailing lists
some BETA drivers has that type of isolation level
 
Adrian Pasik

GeneralRe: Imposible make "IsolationLevel.ReadUncommitted"memberliron.levi29 Mar '09 - 20:20 
Actually - postgresql does not support the read-uncommited isolation level.
 
It converts read-uncommited to read-commited (the more restrictive level) and RepeatableRead to Serializable.
 
This behavior is due to postgresql multiversioning architecture.
 
The driver should have done this automatically (instead of throwing the exception).
 
Liron
GeneralGood articlememberDonsw8 Jan '09 - 10:44 
I just wrote one silimar article Smile | :) using postgres. It is a good db.
QuestionHow to save a image file and put on a web page.memberDavidRRR11 Dec '08 - 10:57 
How to save a image file and put on a web page. Confused | :confused: Confused | :confused: Confused | :confused: Confused | :confused:
AnswerRe: How to save a image file and put on a web page.memberAdrian Pasik12 Dec '08 - 3:58 
If you want to store binary data in postgreSQL search for "Large Objects" in documentation. If it is for images i personally like to store metadata in DBase ie "entry.jpg" | "/home/pguser/img/something.jpg" when i'm developing web page. For desktop application i didn't need funcionality like that, but yes that is a problem. In C# I would try this (taken from Npgsql driver documentation) :
 
public class c
{
    public static void Main(String[] args)
    {
        NpgsqlConnection newconn = new NpgsqlConnection("server=localhost;user id=npgsql_tests;password=npgsql_tests");
 
        newcon.Open();
        NpgsqlTransaction t = newcon.BeginTransaction();
        LargeObjectManager lbm = new LargeObjectManager(newcon);
 
        int noid = lbm.Create(LargeObjectManager.READWRITE);
        LargeObject lo =  lbm.Open(noid,LargeObjectManager.READWRITE);
 
        FileStream fs = File.OpenRead(args[0]);
 
        byte[] buf = new byte[fs.Length];
        fs.Read(buf,0,(int)fs.Length);
 
        lo.Write(buf);
        lo.Close();
        t.Commit();
        
        
        t = newcon.BeginTransaction();
        
        lo =  lbm.Open(noid,LargeObjectManager.READWRITE);
        
        FileStream fsout = File.OpenWrite(args[0] + "database");
        
        buf = lo.Read(lo.Size());
        
        fsout.Write(buf, 0, (int)lo.Size());
        fsout.Flush();
        fsout.Close();
        lo.Close();
        t.Commit();
        
        
        DeleteLargeObject(noid);
        
        Console.WriteLine("noid: {0}", noid);
        newcon.Close();
    }
    
    public static void DeleteLargeObject(Int32 noid)
    {
        NpgsqlConnection conn = new NpgsqlConnection("server=localhost;user id=npgsql_tests;password=npgsql_tests");
 
        newcon.Open();
        NpgsqlTransaction t = newcon.BeginTransaction();
        LargeObjectManager lbm = new LargeObjectManager(newcon);
        lbm.Delete(noid);
        
        t.Commit();
        
        newcon.Close();
 
    }
}
 
 
Look at http://npgsql.projects.postgresql.org/docs/manual/UserManual.html[^]
 
Adrian Pasik

Generalc# datasourcememberJan Bekaert20 Nov '08 - 9:31 
Thanks to Adrian for this great article. Very clear and useful.
 
Another thing that I'm trying to find out is how to add a new datasource based on a PostGreSql database to a C# project since PostGreSql is not available in the Data Provider list (in the Data Source Configuration Wizard).
I'm using VS 2008 (but are quite new to it).
Thanks in advance.
 
Greets&Respect,
 
j
GeneralRe: c# datasourcememberAdrian Pasik20 Nov '08 - 9:52 
well...i don't know Smile | :) and i must confess i never use dbase explorer in the IDE simply because i like to have as much coding area as i can.
More of that, most of the 'bundled' data explorers (in VS or in Delphi) are worse than stand alone tools (Aqua, SQL Manager as i mention in the article) and when you open like 4 tables and write 2 SELECTS you end up with no screen space left. I like to press alt-tab rather than scrolling through 10+ tabs Smile | :)
 
Thank for feedback!!
 
Adrian Pasik

GeneralRe: c# datasourcememberkrepak4 Dec '08 - 19:03 
As far as I know NpgSql do not implement DDEX (Data Design Extensibility for Visual Studio) and thus you can not use it as DataSource. Postgres data provider implementation from Devart does. But it costs money.
GeneralRe: c# datasourcememberMuaath8025 Mar '12 - 19:29 
Try This Post:
 
http://fxjr.blogspot.com/2011/05/npgsql-design-time-support-preview.html[^]
GeneralGood selected subjectmemberMember 476538718 Nov '08 - 6:04 
Nice and usefull document and sample.
Thanks.
GeneralRe: Good selected subjectmemberAdrian Pasik18 Nov '08 - 9:08 
Thanks for feedback. You just made my day Smile | :)
 
Adrian Pasik

Generalgeneralbits [modified]memberLeblanc Meneses16 Nov '08 - 7:04 
If someone reading this is just starting out.
 
http://www.varlena.com/varlena/GeneralBits/[^]
 
has examples of most common questions: creating triggers, what is serial, ect.
 
also for those debating about postgresql you can read
http://www.linux-mag.com/id/5679[^]
 
modified on Sunday, November 16, 2008 1:11 PM

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 15 Nov 2008
Article Copyright 2008 by Adrian Pasik
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid