.. _geoserver.postgis.shp_convert:

Converting Shapefile data to PostGIS
------------------------------------

In the previous section SQL scripts were used to load a PostGIS database. Often it more useful to take existing data in file formats such as Shapefile and import them into a PostGIS database. This section covers using the command:`shp2pgsql` utility to convert a Shapefile into a PostGIS table.

#. Navigate to the workshop :file:`data/bayarea` directory.

#. Copy the following files onto the desktop::

     bay_area_parks.shp
     bay_area_parks.shx
     bay_area_parks.dbf
     bay_area_parks.prj

   .. figure:: shp_convert1.jpg

      Copying the bay_area_parks shapefile

#. From the :guilabel:`Start menu`, open a :guilabel:`Command Line Prompt`.

   .. figure:: shp_convert2.jpg

   .. note:: An alternate way of opening a command prompt is to open the :guilabel:`Start Menu` and select :guilabel:`Run...`. In the resulting dialog enter the text "cmd" and clock :guilabel:`OK`.

#. Change directory to the desktop by executing the command line::

      cd Desktop

#. Convert the :file:`bay_area_parks.shp` file to SQL with the :command:`shp2pgsql` utility by executing the command line::

    "C:\Program Files\PostgreSQL\8.2\bin\shp2pgsql.exe" -s 4326 bay_area_parks.shp bay_area_parks > bay_area_parks.sql

   .. figure:: shp_convert3.jpg

      Converting a shapefile to sql with shp2pgsql

   .. warning:: The quotes around the path to :command:`shp2pgsql` are **necessary** because of the space in the file path.

   .. note:: :command:`shp2pgsql` is a utility  used to convert a shapefile into a database table. It comes with every PostGIS installation.

   .. note:: Tab completion is supported by the windows command prompt and can help when specifying the path to shp2pgsql

#. Execute the :file:`bay_area_parks.sql` script against the database by executing the command line::

     "C:\Program Files\PostgreSQL\8.2\bin\psql.exe" -U postgres bayarea -f bay_area_parks.sql

   .. figure:: shp_convert4.jpg

      Loading the result of shp2pgsql into the database

   .. note:: :command:`psql` is a program used to interact with a PostgreSQL database from the command line. The commmand above takes the sql file :file:`bay_are_parks.sql` created by :command:`shp2pgsql`, and executes it against the database, creating the **bay_area_parks** table.

   .. note:: If prompted for a password remember that the password is "postgres"

#. Using skills learned in the :ref:`previous section <geoserver.postgis.gs_table_add>`, create a feature type for the **bay_area_parks** table created in the previous step.

   .. figure:: shp_convert5.jpg

      Creating the bay_area_parks feature type

   .. figure:: shp_convert6.jpg

      Previewing bay_area_parks