アプリケーションが、組み込み静的 SQL と組み合わせて DB2 CLI を使用することは可能であり、かつ望ましいことです。アプリケーション開発者が、DB2 CLI カタログ関数の利点を活用し、パフォーマンスが重要になるアプリケーション処理の部分を最大化したいというシナリオを考えてみてください。 DB2 CLI と組み込み SQL を混合して使用するには、アプリケーションが次の規則に従っていなければなりません。
DB2 CLI では複数接続ができるので、組み込み SQL で作成されたルーチンに対する関数呼び出しを行う前に、 SQLSetConnection() 関数を呼び出さなくてはなりません。このことを行うと、アプリケーションは、組み込み SQL ルーチンが処理を実行する必要のある接続を明示指定することができます。
DB2 CLI アプリケーションがマルチスレッドにされ、また組み込み SQL 呼び出しまたは DB2 の API 呼び出しを作成する場合、各スレッドは 1 つの DB2 コンテキストを持つ必要があります。詳細な説明については、マルチスレッドのアプリケーション作成を参照してください。
次の例では、2 つのデータ・ソースに接続し、 DB2 CLI を使用して組み込み SQL と動的 SQL の両方を実行しているアプリケーションを示しています。
/* ... */ /* allocate an environment handle */ SQLAllocEnv(&henv); /* Connect to first data source */ DBconnect(henv, &hdbc[0]); /* Connect to second data source */ DBconnect(henv, &hdbc[1]); /********* Start Processing Step *************************/ /* NOTE: at this point there are two active connections */ /* set current connection to the first database */ if ( (rc = SQLSetConnection(hdbc[0])) != SQL_SUCCESS ) printf("Error setting connection 1\n"); /* call function that contains embedded SQL */ if ((rc = Create_Tab() ) != 0) printf("Error Creating Table on 1st connection, RC=%d\n", rc); /* Commit transation on connection 1 */ SQLTransact(henv, hdbc[0], SQL_COMMIT); /* set current connection to the second database */ if ( (rc = SQLSetConnection(hdbc[1])) != SQL_SUCCESS ) printf("Error setting connection 2\n"); /* call function that contains embedded SQL */ if ((rc = Create_Tab() ) != 0) printf("Error Creating Table on 2nd connection, RC=%d\n", rc); /* Commit transation on connection 2 */ SQLTransact(henv, hdbc[1], SQL_COMMIT); /* Pause to allow the existance of the tables to be verified. */ printf("Tables created, hit Return to continue\n"); getchar(); SQLSetConnection(hdbc[0]); if (( rc = Drop_Tab() ) != 0) printf("Error dropping Table on 1st connection, RC=%d\n", rc); /* Commit transation on connection 1 */ SQLTransact(henv, hdbc[0], SQL_COMMIT); SQLSetConnection(hdbc[1]); if (( rc = Drop_Tab() ) != 0) printf("Error dropping Table on 2nd connection, RC=%d\n", rc); /* Commit transation on connection 2 */ SQLTransact(henv, hdbc[1], SQL_COMMIT); printf("Tables dropped\n"); /********* End Processing Step ***************************/ /* ... */ /************* Embedded SQL Functions ******************************* ** This would normally be a seperate file to avoid having to * ** keep precompiling the embedded file in order to compile the DB2 CLI * ** section. * ************************************************************************/ #include "sql.h" #include "sqlenv.h" EXEC SQL INCLUDE SQLCA; int Create_Tab( ) { EXEC SQL CREATE TABLE mixedup (ID INTEGER, NAME CHAR(10)); return( SQLCODE); } int Drop_Tab( ) { EXEC SQL DROP TABLE mixedup; return( SQLCODE); }