python3
yum install python3 python3-pip -y
gdal-3.6.2
参考编译postgis
python安装gdal
export CPLUS_INCLUDE_PATH=/usr/local/gdal-3.6.2/include
export C_INCLUDE_PATH=/usr/local/gdal-3.6.2/include
export LDFLAGS="-L/usr/local/gdal-3.6.2/lib64"
pip3 install gdal==3.6.2
python导入gdb脚本
from osgeo import ogr
import psycopg2db_name = 'filegdb' #瀚高数据库postgis
db_user = 'postgres'
db_password = 'postgres'
db_host = '192.168.110.217'
db_port = '5432' # PostGIS 通常使用的端口号# 连接到PostgreSQL数据库
conn = psycopg2.connect("dbname='filegdb' user='postgres' host='192.168.110.217' password='postgres'")
cur = conn.cursor()# 打开File Geodatabase文件
filegdb_path = "/opt/test_highgo.gdb"
filegdb_driver = ogr.GetDriverByName("FileGDB")
filegdb_dataset = filegdb_driver.Open(filegdb_path, 0)if filegdb_dataset is None:print("Failed to open FileGDB.")exit(1)# 获取File Geodatabase中的图层
num_layers = filegdb_dataset.GetLayerCount()
for i in range(num_layers):layer = filegdb_dataset.GetLayerByIndex(i)# 获取图层中的字段layer_defn = layer.GetLayerDefn()num_fields = layer_defn.GetFieldCount()field_names = [layer_defn.GetFieldDefn(j).GetName() for j in range(num_fields)]field_names_str = ", ".join(field_names)# 创建PostGIS表table_name = layer.GetName().lower()create_table_query = "CREATE TABLE {} (id SERIAL PRIMARY KEY, geom geometry, {})".format(table_name, ", ".join("{} VARCHAR".format(name) for name in field_names))cur.execute(create_table_query)conn.commit()# 从File Geodatabase中读取要素,并插入到PostGIS表中for feature in layer:geometry = feature.GetGeometryRef()wkt = geometry.ExportToWkt()values = [wkt] + [feature.GetField(name) for name in field_names]insert_query = "INSERT INTO {} (geom, {}) VALUES (ST_GeomFromText(%s, 4326), {})".format(table_name, field_names_str, ", ".join(["%s"] * len(field_names)))cur.execute(insert_query, values)conn.commit()# 关闭数据库连接
cur.close()
conn.close()
实例二
# import os
import subprocess# 设置GDB文件路径和数据库连接信息
gdb_path = r'/opt/test_highgo.gdb'
db_name = 'filegdb' #瀚高数据库postgis
db_user = 'postgres'
db_password = 'postgres'
db_host = '192.168.110.217'
db_port = '5432' # PostGIS 通常使用的端口号# 获取GDB中所有图层的名称
def get_layer_names(gdb_path):layers = []cmd = ['ogrinfo', '-so', gdb_path]# 使用subprocess.run来执行命令 获取gdb内的图层信息output = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,errors='ignore')# output.stdout.splitlines() 读取结果,将结果按行分割成字符串列表for line in output.stdout.splitlines():#逐行读取,当行内含有'Layer'字符时,进行信息提取if 'Layer' in line:layers.append(line.split(':')[1].strip().split('(')[0].strip())print(line)return layers# 批量导入图层到PostGIS
def import_layers_to_postgis(gdb_path, pg_conn_str):for layer in get_layer_names(gdb_path):if not layers:print("No layers found in the specified GDB path.")return#command = f'ogr2ogr -f "PostgreSQL" PG:"{pg_conn_str}" {gdb_path} -nln {layer} -overwrite {layer} -progress -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES'command = 'ogr2ogr'args = ['-f', 'PostgreSQL','PG:host=192.168.110.217 port=5432 user=postgres password=postgres dbname=filegdb','/opt/test_highgo.gdb','-overwrite', '-progress','-nln', layer,'-lco', 'GEOMETRY_NAME=geom','--config', 'PG_USE_COPY', 'YES']full_command = [command] + argsprint(full_command) print(f'Importing layer {layer}...')importdb = subprocess.run(full_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, errors='ignore')# 运行函数
#拼接一个连接地址
pg_conn_str="host="+db_host+" port="+db_port+" user="+db_user+" password="+db_password+" dbname="+db_name
import_layers_to_postgis(gdb_path, pg_conn_str)
执行
[root@baidu bin]# python3 gdb2postgis.py
Layer: AGNP (Point)
Layer: BOUL (Multi Line String)
Layer: HYDA (Multi Polygon)
Layer: ChinaSheng (Multi Polygon)
['ogr2ogr', '-f', 'PostgreSQL', 'PG:host=192.168.110.217 port=5432 user=postgres password=postgres dbname=filegdb', '/opt/test_highgo.gdb', '-progress', '-overwrite', '-nln', 'AGNP', '-lco', 'GEOMETRY_NAME=geom', '--config', 'PG_USE_COPY', 'YES']
Importing layer AGNP...
['ogr2ogr', '-f', 'PostgreSQL', 'PG:host=192.168.110.217 port=5432 user=postgres password=postgres dbname=filegdb', '/opt/test_highgo.gdb', '-progress', '-overwrite', '-nln', 'BOUL', '-lco', 'GEOMETRY_NAME=geom', '--config', 'PG_USE_COPY', 'YES']
Importing layer BOUL...
['ogr2ogr', '-f', 'PostgreSQL', 'PG:host=192.168.110.217 port=5432 user=postgres password=postgres dbname=filegdb', '/opt/test_highgo.gdb', '-progress', '-overwrite', '-nln', 'HYDA', '-lco', 'GEOMETRY_NAME=geom', '--config', 'PG_USE_COPY', 'YES']
Importing layer HYDA...
['ogr2ogr', '-f', 'PostgreSQL', 'PG:host=192.168.110.217 port=5432 user=postgres password=postgres dbname=filegdb', '/opt/test_highgo.gdb', '-progress', '-overwrite', '-nln', 'ChinaSheng', '-lco', 'GEOMETRY_NAME=geom', '--config', 'PG_USE_COPY', 'YES']
Importing layer ChinaSheng...