... Or how to upload an ESRI Shapefile to PostGIS.
I 've often been asked how to copy data from a shapefile to a postgis database. postgis comes with a CommandLine-tool for this (shp2pgsql.exe ), but all it does is generate a huge SQL-textfile that you will need to run afterwards-not very efficient I think-especially with the ascii-Representation of the geometry. furthermore I 've had several problems with it regarding into international letters in the attributes.
So why not try to let npgsql and sharpmap do the job?
I 've been working a bit with a small tool that makes it easy to upload an entire shapefile to a PostgreSQL/postgis database using sharpmap.
Below are some of the postgis/sharpmap related Code explained:
First we create a npgsql connection
The next step is to add a geometry column (see in the full source on how you create the table with all the attributes ). in this case we set the spatial reference ID to '-1' and name the geometry column 'geom '.
Command. commandtext = "select addgeometrycolumn ('', 'mytable', 'geom ','-1', 'ry ry', 2 );";
Command. executenonquery ();
Now we are ready to upload to the database, so lets get hold of that shapefile! First we set up a datasource:
Sharpmap. Data. providers. shapefile SHP = new sharpmap. Data. providers. shapefile (@ "C:/data/myshape. SHP", false );
We can now query all the feature object IDs, by using an extents-query on the full extents:
Conn. open ();
List <uint> indexes = SHP. getobjectidsinview (SHP. getextents ());
... And then loop through all the features:
Foreach
(Uint idx in indexes)
{
SharpMap. Data. FeatureDataRow feature = shp. GetFeature (idx );
Command. CommandText = "insert into/" myTable/"(/" geom/") VALUES (GeomFromWKB (: geom,: srid ));";
Command. Parameters. Add (": geom", NpgsqlTypes. NpgsqlDbType. Bytea );
Command. Parameters [": geom"]. Value = feature. Geometry. AsBinary (); // Add the geometry as Well-Known Binary
Command. Parameters. Add (": srid", NpgsqlTypes. NpgsqlDbType. Integer );
// Set the SRID of the geometry-this must match the SRID we used when the column was created
Command. Parameters [": srid"]. Value =-1;
// TODO: Add parameters for remaining columns if nessesary (in that case alter the INSERT commandtext accordingly)
Command. ExecuteNonQuery ();
}
// Clean up
Conn. Close ();
Shp. Close ();
... And that is all there is to it!
The great thing about this, is that it is easy to change this to take any other SharpMap datasource and upload as well. and with Christians OGR extension you can suddenly upload a bunch of datasource directly to PostGIS.
Download the full source and compiled binaries here: Shape2Pgsql.zip (26,200 KB) (updated transfer l 5432 6) NpgsqlConnection conn = new NpgsqlConnection ("Server = localhost; Port =; User Id = username; password = password; Database = myGisDB ;")
NpgsqlCommand command = new NpgsqlCommand ();
Command. Connection = conn;