GeoTools对mysql数据库的读写操作


GeoTools对mysql数据库的读写操作

本文是本人花了两天时间看geotools源码文档和api文档写出来的,希望尊重劳动成果,转载必须注明链接和出处。:

  • **geotools不需要我再介绍了,一个开源GIS代码库,编程语言为java。对于mysql的读写操作,可以使用sql语句,但是比较繁琐,繁琐在建立字段,确定字段类型等方面,导师在要求使用geotools读写,不建议使用sql语句操作数据库,更重要的原因是GIS要接触很多地理空间数据,比如点、线、面、多线、多面。在mysql字段类型上建立很繁琐。举个例子:
CREATE TABLE `tif2db1` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `dataid` int(13) NOT NULL,
  `FileName` varchar(1024) NOT NULL,
  `FilePath` varchar(1024) NOT NULL,
  `FileSize` int(13) NOT NULL,
  `satellite` varchar(1024) NOT NULL,
  `acquisitionTime` timestamp NULL DEFAULT NULL,
  `archiveTime` timestamp NULL DEFAULT NULL,
  `CellSizexy` varchar(25) NOT NULL,
  `Columns` double(12,6) DEFAULT NULL,
  `Rows` double(12,6) DEFAULT NULL,
  `BandsNumber` int(13) NOT NULL,
  `RasterFormat` varchar(25) NOT NULL,
  `ExtentTop` double(15,6) DEFAULT NULL,
  `ExtentLeft` double(15,6) DEFAULT NULL,
  `ExtentBottom` double(15,6) DEFAULT NULL,
  `ExtentRight` double(15,6) DEFAULT NULL,
  `Shape` polygon DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
  • 看看上面Shape字段,不同于double、varchar等常规类型,是polygon面类型,实际意义是矩形的四个顶点所围成的四边形。写数据库代码主要参考了geotools-17.0-userguide里的函数。下面贴出使用geotools读写数据到mysql的代码。**
    这里写图片描述
package readTifftest;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.geotools.data.FeatureWriter;
import org.geotools.data.Transaction;
import org.geotools.data.mysql.MySQLDataStoreFactory;
import org.geotools.data.store.ContentEntry;
import org.geotools.feature.NameImpl;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.jdbc.JDBCDataStore;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LinearRing;
import com.vividsolutions.jts.geom.Polygon;

public class Image2Db {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		CreateSchema();

	}
	public static void CreateSchema(){
		//简单要素类型用于设置名称、增加属性和几何属性
		SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();

		//set the name
		b.setName( "Flag" );//表名

		//add some properties
		b.add( "FileName", String.class );
		b.add( "FileSize", Integer.class );
		b.add( "Rows", Double.class );

		//add a geometry property
		//b.setCRS( DefaultGeographicCRS.WGS84 ); // set crs first
		b.add( "Shape", Polygon.class ); // then add geometry

		//build the type
		final SimpleFeatureType FLAG = b.buildFeatureType();
		//the type, schema = ( name:String, classification:Integer, height:Double, location:Point)
		SimpleFeatureType schema = FLAG;
		MySQLDataStoreFactory factory1 = new MySQLDataStoreFactory();
		//FeatureSource fsBC1;
		Map<String,Object> params1 = new HashMap<String, Object>();
		params1.put("dbtype", "****");//此**出填写数据库名称,如mysql
		params1.put("host", "***");  //此**出填写本机ip
		params1.put("port", new Integer(3306));
		params1.put("database", "***");//此**出填写需要连接的数据库
		params1.put("user", "root");
		params1.put("passwd", "*****");////此**出填写要连接的mysql密码
		JDBCDataStore ds;
		try {
			ds = (JDBCDataStore) factory1.createDataStore(params1);
			if(ds !=null){
				System.out.println("系统连接到位于localhost的空间数据库成功!");
			}else{
				System.out.println("系统连接到位于localhost的空间数据库失败!请检查相关参数!");
			}
			ContentEntry entry = ds.getEntry(new NameImpl(null, schema
					.getTypeName()));
			if (entry != null) {
				ds.removeSchema(schema.getTypeName().toLowerCase());
			}
			ds.createSchema(schema);//在mysql创建表

			//开始写入数据
			FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds
					.getFeatureWriter(schema.getTypeName().toLowerCase(),
							Transaction.AUTO_COMMIT);

//			SimpleFeatureIterator itertor = featureSource.getFeatures()
//					.features();

			//create the builder
			SimpleFeatureBuilder builder = new SimpleFeatureBuilder(schema);
			//为polygon面类型添加数据
			GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
			Coordinate[] coords  =
			   new Coordinate[] {new Coordinate(4, 0), new Coordinate(2, 2),
			                     new Coordinate(4, 4), new Coordinate(6, 2), new Coordinate(4, 0) };
			LinearRing ring = geometryFactory.createLinearRing( coords );
			LinearRing holes[] = null; // use LinearRing[] to represent holes
			Polygon polygon = geometryFactory.createPolygon(ring, holes );
			
			//add the values
			builder.add( "J46D001001" );
			builder.add( 367);
			builder.add( 23069 );
			builder.add( polygon);

			//build the feature with provided ID
			SimpleFeature feature = builder.buildFeature( "fid.1" );
			// CoordinateReferenceSystem crs = CRS.decode("EPSG:4326");
					
				writer.hasNext();
				SimpleFeature feature1 = writer.next();		
				feature1.setAttributes(feature.getAttributes());
				writer.write();			
			//itertor.close();

			writer.close();
			ds.dispose();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
	}
}

好了,暂时就写到这了,我的geotools库是geotools-17.0,还比较新,java开发平台是eclipse。博文不断更新中,关系GIS方向的小伙伴互相交流,本人邮箱:a928594131@163.com。转载请注明。
快过年了,还在帝都,能早点回家就好了。

转载自:https://blog.csdn.net/m0_37821031/article/details/79060182

You may also like...