I don't have a lot to say, but this is my little bit.

Tuesday, April 20, 2010

Connect To PostgreSQL In C#

Here is an example of how to connect to a PostgreSQL database from Visual Studio and C#. This example uses the OdbcConnection class and the psqlODBC driver.

This example makes a PostGIS select statement, but the statement could be anything.

string connectionString = @"Driver={PostgreSQL UNICODE};Server=localhost;Port=5432;Database=name-of-db;Uid=name-of-db-user;Pwd=password-for-that-user;";
string selectStatement = "SELECT tzid from lookup_zone where ST_Intersects(ST_GeomFromEWKT('SRID=4326;POINT(" + lon + " " + lat + ")'), geom);";

OdbcConnection connection = new OdbcConnection(connectionString);
connection.Open();

DataSet dataSet = new DataSet();
OdbcDataAdapter dataAdapter = new OdbcDataAdapter();
dataAdapter.SelectCommand = new OdbcCommand(selectStatement, connection);
dataAdapter.Fill(dataSet);
connection.Close();

string firstResult = dataSet.Tables[0].Rows[0][0].ToString();

No comments:

Post a Comment