Skip to end of metadata
Go to start of metadata

This example shows how to add new feature data into a MySQL database.

First you have to create the mockup database and then the roads table with the following script

Then you can access and update the database by the following code

  • No labels


  1. If you get a:

    Exception in thread "main" java.lang.ClassCastException:

    the problem may not be with your code, the problem is with the SQL table definition:

    CREATE TABLE roads (
       fid varchar(255) PRIMARY KEY,
       the_geom GEOMETRY
  2. Here's an updated version of the original example that seems to work with GeoTools 2.6. It is no longer necessary to create the table separately as this is now done programmatically. The code:

    try {
        //feature : type creation
        AttributeDescriptor roadWidth = AttributeTypeFactory.newAttributeType("width",Integer.class);
        AttributeDescriptor geom = AttributeTypeFactory.newAttributeType("the_geom",LineString.class);
        SimpleFeatureType ftRoad = FeatureTypes.newFeatureType(new AttributeDescriptor[] { roadWidth, geom  }, "roads");
        // feature : instance creation
        WKTReader wktReader = new WKTReader();
        LineString geometry = (LineString)"LINESTRING (0 0, 10 10)");
        Float width = new Float(10);
        SimpleFeatureBuilder sfBuilder = new SimpleFeatureBuilder(ftRoad);
        sfBuilder.addAll(new Object[] { width,geometry });// the order must be compliant with the one in MySQL
        SimpleFeature theRoad = sfBuilder.buildFeature("myRoad");

        // datastore creation
        MySQLDataStoreFactory factory = new MySQLDataStoreFactory();
        Map<String,String> params = new HashMap<String,String>();
        params.put( "database", "name_of_database" );
        params.put( "dbtype", "mysql");
        params.put( "host", "localhost");
        params.put( "port", "3306");
        params.put( "user", "someuser");
        params.put( "passwd", "somepassword");
        JDBCDataStore datastore = factory.createDataStore(params);
        //road table creation
        //road table population
        ContentFeatureSource fsRoads = datastore.getFeatureSource("roads");
        FeatureReader<SimpleFeatureType,SimpleFeature> aReader = DataUtilities.reader(new SimpleFeature[] { theRoad });
        while(aReader.hasNext()) {
    } catch(Exception e) {