Insert.py
2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# 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()