geotools學習之連線資料庫並獲取資料
阿新 • • 發佈:2018-12-20
本文主要講連線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")); } } }