PostGIS_example.java
package rgeo.lesson_12; 
 
import java.sql.*; 
import java.util.*; 
 
import org.postgis.*; 
import org.postgresql.util.PGobject; 
 
/** 
 * Created by Antonio Rodriges, rodriges@wikience.org on 3/10/2016. 
 * Code based on http://postgis.net/docs/manual-2.2/ch06.html#idp55475552 
 */ 
public class PostGIS_example { 
    public static void main(String args[]) { 
 
        java.sql.Connection conn; 
 
        try { 
            /* 
            * Load the JDBC driver and establish a connection. 
            */ 
 
            Class.forName("org.postgresql.Driver"); 
 
            // NOTE: I run PostgreSQL on 5400 port - not standard 
            // NOTE: postgis_example - is the database name 
            String url = "jdbc:postgresql://localhost:5400/postgis_example"; 
 
            // NOTE: 1111 - password (usually specified during setup) 
            conn = DriverManager.getConnection(url, "postgres", "1111"); 
 
            /* 
            * Add the geometry types to the connection. Note that you 
            * must cast the connection to the pgsql-specific connection 
            * implementation before calling the addDataType() method. 
            */ 
 
            ((org.postgresql.PGConnection) conn).addDataType("geometry", (Class<? extends PGobject>) Class.forName("org.postgis.PGgeometry")); 
            ((org.postgresql.PGConnection) conn).addDataType("box3d", (Class<? extends PGobject>) Class.forName("org.postgis.PGbox3d")); 
 
            /* 
            * Create a statement and execute a select query. 
            */ 
 
            Statement s = conn.createStatement(); 
            ResultSet r = s.executeQuery("select geom,id from geotable"); 
 
            while (r.next()) { 
 
                /* 
                 * Retrieve the geometry as an object then cast it to the geometry type. 
                 * Print things out. 
                 */ 
                PGgeometry geom = (PGgeometry) r.getObject(1); 
                int id = r.getInt(2); 
                System.out.println("Row " + id + ":"); 
                System.out.println(geom.toString()); 
            } 
 
            s.close(); 
            conn.close(); 
 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 
}