Click here to view and discuss this page in DocCommentXchange. In the future, you will be sent there automatically.

SQL Anywhere 10.0.1 » UltraLite - C and C++ Programming » Developing Applications Using Embedded SQL

Introduction to embedded SQL development Next Page

Example of embedded SQL


Embedded SQL is an environment that is a combination of C/C++ program code and pseudo-code. The pseudo-code that can be interspersed with traditional C/C++ code is a subset of SQL statements. A preprocessor converts the embedded SQL statements into function calls that are part of the actual code that is compiled to create the application.

Following is a very simple example of an embedded SQL program. It illustrates updating an UltraLite database record by changing the surname of employee 195.

#include <stdio.h>
EXEC SQL INCLUDE SQLCA;
main( )
{
   db_init( &sqlca );
   EXEC SQL WHENEVER SQLERROR GOTO error;
   EXEC SQL CONNECT "DBA" IDENTIFIED BY "sql";
   EXEC SQL UPDATE employee
      SET emp_lname = 'Johnson'
      WHERE emp_id = 195;
   EXEC SQL COMMIT;
   EXEC SQL DISCONNECT;
   db_fini( &sqlca );
   return( 0 );
   error:
      printf( "update unsuccessful: sqlcode = %ld\n",
         sqlca.sqlcode );
      return( -1 );
}

Although this example is too simplistic to be useful, it illustrates the following aspects common to all embedded SQL applications:

Initialization

The above sample code illustrates initialization statements that must be included before working with the data in an UltraLite database:

  1. Define the SQL Communications Area, SQLCA, using the following command:

    EXEC SQL INCLUDE SQLCA;

    This definition must be the first embedded SQL statement, so a natural place for it is the end of the include list.

    If you have multiple .sqc files in your application, each file must have this line.

  2. The first database action must be a call to an embedded SQL library function named db_init. This function initializes the UltraLite runtime library. Only embedded SQL definition statements can be executed before this call.

    See db_init function.

  3. You must use the SQL CONNECT statement to connect to the UltraLite database.

Preparing to exit

The above sample code demonstrates the sequence of calls required when preparing to exit:

  1. Commit or rollback any outstanding changes.

  2. Disconnect from the database.

  3. End your SQL work with a call to a library function named db_fini.

When you exit, any uncommitted database changes are automatically rolled back.

Error handling

There is virtually no interaction between the SQL and C code in this example. The C code only controls the flow of the program. The WHENEVER statement is used for error checking. The error action, GOTO in this example, is executed whenever any SQL statement causes an error.


Structure of embedded SQL programs