本文主要講連接postgis數據庫,並且獲得數據,這里的數據不拘泥postgis數據庫
一、demo示例
package org.geotools.WPS;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.postgis.PostgisNGDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.opengis.feature.simple.SimpleFeature;
public class postgis {
/**
* @param dbtype: 數據庫類型,postgis or mysql
* @param host: ip地址
* @param port: 端口號
* @param database: 需要連接的數據庫
* @param userName: 用戶名
* @param password: 密碼
* @param tableName: a需要連接的表名
* @return: 返回為FeatureCollection類型
*/
private static SimpleFeatureCollection connAndgetCollection(String dbtype, String host, String port,
String database, String userName, String password,String tableName) {
Map<String, Object> params = new HashMap<String, Object>();
DataStore pgDatastore=null;
params.put(PostgisNGDataStoreFactory.DBTYPE.key, dbtype); //需要連接何種數據庫,postgis or mysql
params.put(PostgisNGDataStoreFactory.HOST.key, host);//ip地址
params.put(PostgisNGDataStoreFactory.PORT.key, new Integer(port));//端口號
params.put(PostgisNGDataStoreFactory.DATABASE.key, database);//需要連接的數據庫
params.put(PostgisNGDataStoreFactory.SCHEMA.key, "public");//架構
params.put(PostgisNGDataStoreFactory.USER.key, userName);//需要連接數據庫的名稱
params.put(PostgisNGDataStoreFactory.PASSWD.key, password);//數據庫的密碼
SimpleFeatureCollection fcollection=null;
try {
//獲取存儲空間
pgDatastore = DataStoreFinder.getDataStore(params);
//根據表名獲取source
SimpleFeatureSource fSource=pgDatastore.getFeatureSource(tableName);
if (pgDatastore != null) {
System.out.println("系統連接到位於:" + host + "的空間數據庫" + database
+ "成功!");
fcollection=fSource.getFeatures();
} else {
System.out.println("系統連接到位於:" + host + "的空間數據庫" + database
+ "失敗!請檢查相關參數");
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("系統連接到位於:" + host + "的空間數據庫" + database
+ "失敗!請檢查相關參數");
}
return fcollection;
}
public static void main(String[] args) {
//調用方法
SimpleFeatureCollection featureColls=postgis.connAndgetCollection("postgis", "localhost", "5432", "sqlView", "postgres", "postgres","roa_4m");
SimpleFeatureIterator itertor = featureColls.features();
//循環讀取feature,itertor.hasNext()表示游標下一個是否有數據,有返回ture,否則為false
while (itertor.hasNext())
{
//獲取每一個要素
SimpleFeature feature = itertor.next();
System.out.println(feature.getAttribute("roa_4m_id"));
}
}
}