Click here to Skip to main content
Click here to Skip to main content
 
Add your own
alternative version
Go to top

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

, 15 Nov 2008
In this article, I would like to show you step by step how to use this fantastic database in your C# application.
afppostsrc.zip
PostgreSQLTEst
MultiCtrls.dll
PostgreSQLTEst
bin
obj
Release
PostgreSQLTEst.exe
PostgreSQLTEst.csproj.user
Properties
Settings.settings
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
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;
			}
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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

Share

About the Author

Adrian Pasik
Software Developer Agilion Consulting
Poland Poland
I specialize at C#, developing Enterprise solutions. I have some knowledge of ASP.NET MVC - looking forward to use it together with Typescript.
Follow on   LinkedIn

| Advertise | Privacy | Mobile
Web02 | 2.8.140905.1 | Last Updated 15 Nov 2008
Article Copyright 2008 by Adrian Pasik
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid