Click here to Skip to main content
15,879,535 members
Articles / Programming Languages / SQL

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

Rate me:
Please Sign up or sign in to vote.
4.92/5 (80 votes)
15 Nov 2008BSD4 min read 768.6K   15.9K   112  
In this article, I would like to show you step by step how to use this fantastic database in your C# application.
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


Written By
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.

Comments and Discussions