Created
June 28, 2023 18:56
-
-
Save jrgavilanes/875386e10e00e275f9de59a3498aba16 to your computer and use it in GitHub Desktop.
graba geo poligono en postgres con python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import psycopg2 | |
from psycopg2.extras import RealDictCursor | |
from shapely.geometry import Polygon | |
# Establecer la conexión a la base de datos | |
conn = psycopg2.connect( | |
host="localhost", | |
database="sig_local", | |
user="janrax", | |
password="janrax" | |
) | |
# Crear un cursor para ejecutar consultas | |
cursor = conn.cursor(cursor_factory=RealDictCursor) | |
# Crear el polígono utilizando la biblioteca Shapely | |
poligono = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)]) | |
# Definir los valores para insertar en la tabla | |
valores = { | |
'geom': poligono.wkt # Convertir el polígono a formato WKT (Well-Known Text) | |
} | |
# Construir la consulta SQL para insertar el polígono en la tabla | |
consulta = "INSERT INTO sig.poligonos (geom) VALUES (ST_SetSRID(ST_GeomFromText(%(geom)s), 4326))" | |
# Ejecutar la consulta | |
cursor.execute(consulta, valores) | |
# Confirmar los cambios en la base de datos | |
conn.commit() | |
# Cerrar la conexión y el cursor | |
cursor.close() | |
conn.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment