GDAL / OGR Python 바인딩에서 PostgreSQL / PostGIS 오류를 잡는 방법?


10

쿼리가 실패한 후 OGR에서 PostgreSQL 출력 오류 메시지를 포착 할 수 있습니까?

예를 들어

conn.ExecuteSQL('SELECT * FROM non_existing_table;')

Postgres에서 이것은 오류 메시지를 반환합니다 :

"Error: relation 'non_existing_table' does not exist."

ogr에서 우리는 표준을 얻습니다.

"Error: current transaction is aborted, commands ignored until end of transaction block"

Postgres 오류 메시지를 잡거나 파싱 할 수 있다면 보너스가 될 것입니다. SWIG / CPL에 대해 읽은 내용을 고려할 때 약간의 시간이 걸리지 만 누군가 아이디어가 있는지 물어볼 가치가 있다고 생각합니다. 이상적으로는 파이썬에 있지만 C / C ++ 주석도 사용하겠습니다!

감사.

답변:


6

PostgreSQL 데이터 소스에 대한 오류보고가 개선 된 GDAL / OGR 1.9.x로 업그레이드해야합니다.

$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from osgeo import ogr
>>> ogr.UseExceptions()
>>> ds = ogr.Open('pg:dbname=autotest')
>>> ds.ExecuteSQL("SELECT * FROM non_existing_table")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/dist-packages/osgeo/ogr.py", line 699, in ExecuteSQL
    return _ogr.DataSource_ExecuteSQL(self, *args, **kwargs)
RuntimeError: ERREUR:  la relation « non_existing_table » n'existe pas
LINE 1: DECLARE executeSQLCursor CURSOR for SELECT * FROM non_existi...

1

psycopg2를 사용하는 경우 다음 코드와 같이 "시도"기능으로 오류 메시지를 쉽게 인쇄 할 수 있습니다. 코드는 다시 작성하지 않기 위해 zetcode.com 에서 가져 왔습니다 ...

#!/usr/bin/python
# -*- coding: utf-8 -*-

import psycopg2
import sys


con = None

try:

    con = psycopg2.connect(database='testdb', user='janbodnar') 
    cur = con.cursor()
    cur.execute('SELECT version()')          
    ver = cur.fetchone()
    print ver    


except psycopg2.DatabaseError, e:
    print 'Error %s' % e    
    sys.exit(1)


finally:

    if con:
        con.close()

나는 그것이 당신에게 도움이되기를 바랍니다 ...


감사합니다 Aragon, 예 Psycopg2는 훌륭한 라이브러리이지만 ogr을 통해 비슷한 것이 가능한지 알고 싶습니다. 지오메트리 작업을 처리하려면 ogr이 필요하며 다른 API를 사용하기 위해 연결을 복제하지는 않겠습니다.
— Tomas
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.