Advertisement
Guest User

Untitled

a guest
Nov 30th, 2016
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. import java.sql.*;
  2. import java.util.*;
  3. import java.lang.*;
  4. import org.postgis.*;
  5.  
  6. public class JavaGIS {
  7.  
  8. public static void main(String[] args) {
  9. java.sql.Connection conn;
  10. try {
  11. Class.forName("org.postgresql.Driver");
  12. String url = "jdbc:postgresql://localhost:5432/gis_data";
  13. conn = DriverManager.getConnection(url, "postgres", "");
  14.  
  15. ((org.postgresql.PGConnection)conn).addDataType("geometry",Class.forName("org.postgis.PGgeometry"));
  16. ((org.postgresql.PGConnection)conn).addDataType("box3d",Class.forName("org.postgis.PGbox3d"));
  17.  
  18. Polygon geo = new Polygon(
  19. new LinearRing[] {
  20. new LinearRing(
  21. new Point[] {
  22. new Point(-1.0d, -1.0d, 0.5d),
  23. new Point( 1.0d, -1.0d, 0.0d),
  24. new Point( 1.0d, 1.0d, -0.5d),
  25. new Point(-1.0d, 1.0d, 0.0d),
  26. new Point(-1.0d, -1.0d, 0.5d)
  27. }
  28. )
  29. }
  30. );
  31. PreparedStatement s = conn.prepareStatement("INSERT INTO sample_table (key_value, large_poly) VALUES (?, ?)");
  32. s.setString(1, "poly1");
  33. s.setObject(2, new PGgeometry(geo));
  34.  
  35. int rows = s.executeUpdate();
  36.  
  37. if (rows > 0) {
  38. System.out.println(" Successful insert! ");
  39. } else {
  40. System.out.println(" Failed insert!");
  41. }
  42. s.close();
  43.  
  44. Statement qs = conn.createStatement();
  45. ResultSet r = qs.executeQuery("SELECT key_value, large_poly FROM sample_table");
  46. while( r.next() ) {
  47. /*
  48. * Retrieve the geometry as an object then cast it to the geometry type.
  49. * Print things out.
  50. */
  51. String key = r.getString(1);
  52. PGgeometry geom = (PGgeometry)r.getObject(2);
  53.  
  54. if (geom.getGeoType() == Geometry.POLYGON) {
  55. System.out.println("Found a polygon with key " + key);
  56. } else {
  57. System.out.println("Found a PostGIS geometry object " + geom.getGeoType() + " having key " + key);
  58. }
  59. }
  60. qs.close();
  61. conn.close();
  62. }
  63. catch( Exception e ) {
  64. e.printStackTrace();
  65. }
  66. }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement