cx_oracle Error handling issue

2019-08-22 21:42发布

问题:

I'm trying to execute the following query in cx_Oracle but get the following error while executing:

    print 'Error.code    =', error.code
AttributeError: 'str' object has no attribute 'code'

Code:

try:
    conn.exec("Select * from table1")
except cx_Oracle.DatabaseError, ex:
    error, = ex.args    
    print 'Error Inserting Field Base'
    print 'Error.code    =', error.code
    print 'Error.message =', error.message
    print 'Error.offset  =', error.offset
    conn.rollback()

回答1:

I think this is a better way to do it. I am not sure what is the issue with your code without getting more details but try this out and I hope this shall be useful.

In [10]: connstr="%s/%s@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=%s)(PORT=%d))(CONNECT_DATA=(SERVICE_NAME=%s)))" % tuple(db[0:5])
In [11]: try: 
   ....:     conn = cx_Oracle.connect(connstr)
   ....:     query = 'select * from table_name limit 1;'
   ....:     curs = conn.cursor()
   ....:     curs.arraysize=50
   ....:     curs.execute(query)
   ....:     curs.close()
   ....:     conn.close()
   ....: except cx_Oracle.DatabaseError, ex:
   ....:     error, = ex.args
   ....:     print 'Error.code =', error.code
   ....:     print 'Error.message =' , error.message
   ....:     print 'Error.offset =', error.offset
   ....:     conn.rollback()
   ....:     
Error.code = 933
Error.message = ORA-00933: SQL command not properly ended

Error.offset = 31