Wednesday, January 18, 2012

Adding PostgreSQL db to Asp.Net web project on Windows 7

Last night I was trying to connect an existing Asp MVC 3 app to use an PostgreSQL database.  It is using nHibernate, so I'm still going to have to determine if I need to tweak anything there, but for now just wanted to connect properly.

After installing Postgre, I needed to install the ODBC connector in order to establish a connection in my .Net application.  There was a little trick, when I used the ODBC configurator from the Start menu, I didn't see the newly installed ODBC adapter!  WTF?  Turns out, since I was running a 64 bit version of my OS, I had to run c:\windows\syswow64\odbcad32.exe in order to set my new ODBC driver.  There is also another way...

Install NpgSQL adapter, I used the latest .Net 4.0 install.  After referencing the Npg dll in your project (plus an associated Mono dll), you can simply use their wrappers in order to connect, here you can get the gist:

using NpgSQL;
var connstring = String.Format("Server=localhost;Port=5432;User Id=;Password=xxx; Database=DbName;");
var conn = new NpgsqlConnection(connstring);
conn.Open();
const string sql = "SELECT LastName FROM Users ORDER BY LastName LIMIT 10";
var da = new NpgsqlDataAdapter(sql, conn);
var ds = new DataSet();
da.Fill(ds);

2 comments:

ADmin said...
This comment has been removed by a blog administrator.
Unknown said...

The Keshri Software Solutions is a one-stop site for Asp(.)Net Live Project Training. We have successfully completed several batches and all are placed and working in a reputed company.
Our aim is to provide crystal clear concepts and to boost programming & technology skills of candidates through best Live Project
Training.

To know more information please visit once -
Please visit : http://training.ksoftware.co.in/ for more details.