Insert.py 2.3 KB
# coding=utf-8
#author:        4N
#createtime:    2021/6/11
#email:         nheweijun@sina.com

from osgeo.ogr import *
from osgeo import gdal,ogr


def get_info_from_sqlachemy_uri(uri):
    parts = uri.split(":")
    user = parts[1][2:]

    password_list = parts[2].split("@")
    if password_list.__len__() > 2:
        password = "@".join(password_list[:-1])
    else:
        password = parts[2].split("@")[0]
    host = parts[2].split("@")[-1]
    port = parts[3].split("/")[0]
    database = parts[3].split("/")[1]

    return user, password, host, port, database


def open_pg_data_source(iswrite, uri):
    """
    # 获取PostGIS数据源
    :return:
    """
    db_conn_tuple = get_info_from_sqlachemy_uri(uri)
    fn = "PG: user=%s password=%s host=%s port=%s dbname=%s " % db_conn_tuple
    driver = ogr.GetDriverByName("PostgreSQL")
    if driver is None:
        raise Exception("打开PostgreSQL驱动失败,可能是当前GDAL未支持PostgreSQL驱动!")
    ds = driver.Open(fn, iswrite)
    if ds is None:
        raise Exception("打开数据源失败!")
    return ds

# data_path=r"E:\Data\voronoi8000w.gdb"
#
# driver: Driver = ogr.GetDriverByName("OpenFileGDB")
# ds: DataSource = driver.Open(data_path, 0)
# if not ds:
#     raise Exception("打开数据失败!")
#
# layer: Layer = ds.GetLayer(0)
pg_ds:DataSource= open_pg_data_source(1,"postgresql://postgres:chinadci@172.26.99.173:5433/postgres")

pg_layer: Layer = pg_ds.CreateLayer("tg3", None, ogr.wkbUnknown)

feat = ogr.Feature(pg_layer.GetLayerDefn())
point = ogr.Geometry(ogr.wkbPoint)
point.AddPoint(1198054.34, 648493.09)
feat.SetGeometry(point)
pg_layer.CreateFeature(feat)


feat2 = ogr.Feature(pg_layer.GetLayerDefn())

ring = ogr.Geometry(ogr.wkbLinearRing)
ring.AddPoint(1179091.1646903288, 712782.8838459781)
ring.AddPoint(1161053.0218226474, 667456.2684348812)
ring.AddPoint(1214704.933941905, 641092.8288590391)
ring.AddPoint(1228580.428455506, 682719.3123998424)
ring.AddPoint(1218405.0658121984, 721108.1805541387)
ring.AddPoint(1179091.1646903288, 712782.8838459781)



# Create polygon
poly = ogr.Geometry(ogr.wkbPolygon)
poly.AddGeometry(ring)

print(poly.GetEnvelope())

feat2.SetGeometry(poly)
pg_layer.CreateFeature(feat2)


pg_ds.Destroy()