Explicit Error Handling
The program can also handle errors by inspecting values of the SQLCA at various points. For further details, see the SQL Reference Guide.
The following example is functionally the same as the previous example, except that the error handling is hard-coded in Fortran statements.
Example: Explicit error handling
C
C Main error handling program
C
program DbTest
exec sql include sqlca
exec sql begin declare section
integer*2 eno
character*20 ename
integer*1 eage
exec sql end declare section
exec sql declare empcsr cursor for
1 select eno, ename, age
2 from employee
C Exit if database cannot be opened
exec sql connect personnel
if (sqlcod .lt. 0) then
print *, 'Cannot access database'
stop
end if
C Error if cannot open cursor
exec sql open empcsr
if (sqlcod .lt. 0) call ClnUp('OPEN "empcsr"')
print *, 'Some values from the "employee" table'
C The last executable Embedded SQL statement was
C an OPEN, so we know that the value of "sqlcod"
C cannot be SQLERROR or NOT FOUND.
C The following loop is broken by NOT FOUND
C (condition 100) or an
C error
100 exec sql fetch empcsr
1 into :eno, :ename, :age
if (sqlcod .lt. 0) then
call ClnUp('FETCH "empcsr"')
C Do not print the last values twice
else if (sqlcod .ne. 100) then
print *, eno, ename, age
end if
if (sqlcod .eq. 0) goto 100
exec sql close empcsr
exec sql disconnect
end
C
C ClnUp: Error handling subroutine
C (print error and disconnect).
C
subroutine ClnUp(reason)
exec sql include sqlca
exec sql begin declare section
character*(50) reason
character*100 errmsg
exec sql end declare section
print *, 'Aborting because of error in ', reason
exec sql inquire_sql (:errmsg=ERRORTEXT)
print *, errmsg
exec sql disconnect
C Do not return to DbTest
stop
end