Displaying Error Messages After a Database Query

The code for the preceding examples assumes that the queries to the database will always be successful. Unfortunately, this is not always the case. The code below intentionally generates an error because the table referenced in the SQL Select statement does not exist:

declare subroutine msg
$insert XO_Equates
$insert Msg_Equates
 
hXO = XOInstance ("NWIND")
 
hQry = 0
if hXO then
   * create the query handle for the connection handle
   hQry = QryInstance(hXO)
   if hQry then
       
      * force an error - table doesn't exist
      
        Script = "select * from nonexisting_table"
        Flag = QryMethod(hQry, QRY_EXECUTE$, Script)
      if Flag then
         call msg(@window, 'Select Statement executed successfully!')
      end else
         gosub error
      end
      
end else
   gosub error
end
 
* close the query handle
Flag = QryMethod(hQry, QRY_DESTROY$)
* close the connection
Flag = XOMethod(hXO, XO_DESTROY$)
return 0
 
*************************************************************
* Error handling subroutine
Error:
   if hQry then
      Flag = QryMethod(hQry, QRY_GETERROR$, "", "", "",|
                       "",Text)
   end else
      Flag = XOMethod(hXO, QRY_GETERROR$, "", "", "", |
                      "",Text)
   end
   convert @vm to @tm in Text
   Def = ""
   Def<MTEXT$>    = Text
   Def<MCAPTION$> = "ExecuteScript Error"
   Def<MICON$>    = "!"
   Msg(@window, Text)
 
return
*****************************************************************

The error message displays as shown below:

After each query execution (calling QryMethod() using the QRY_EXECUTE$ code), it is good programming practice to test whether or not an error occurred. Test the return code from QryMethod(); if it is not zero, then call a subroutine that retrieves the text of the error message (calling QryMethod() using the QRY_GETERROR$ code) and then outputs the message using the Msg() function.

  • No labels