Using Strings or host-language Variables

From InterBase

Go Up to Using simple CONNECT Statements


Instead of using a database handle, CONNECT can use a database name supplied at run time. The database name can be supplied as either a host-language variable or a hard-coded, quoted string.

The following C code demonstrates how a program accessing only a single database might implement CONNECT using a file name solicited from a user at run time:

. . .
char fname[125];
. . .
printf('Enter the desired database name, including node
and path):\n');
gets(fname);
. . .
EXEC SQL
CONNECT :fname;
. . .
Tip:
This technique is especially useful for programs that are designed to work with many identically structured databases, one at a time, such as CAD/CAM or architectural databases.

Multiple Database Implementation

To use a database specified by the user as a host-language variable in a CONNECT statement in multi-database programs, follow these steps:

  1. Declare a database handle using the following SET DATABASE syntax:
    EXEC SQL
    SET DATABASE handle = COMPILETIME 'dbname';
    
    Here, <handle> is a hard-coded database handle supplied by the programmer, <dbname> is a quoted, hard-coded database name used by gpre during preprocessing.
  2. Prompt the user for a database to open.
  3. Store the database name entered by the user in a host-language variable.
  4. Use the handle to open the database, associating the host-language variable with the handle using the following CONNECT syntax:
    EXEC SQL
    CONNECT :variable AS handle;
    

    The following C code illustrates these steps:

    . . .
    char fname[125];
    . . .
    EXEC SQL
    SET DATABASE DB1 = 'employee.ib';
    printf("Enter the desired database name, including node
    and path):\n");
    gets(fname);
    EXEC SQL
    CONNECT :fname AS DB1;
    . . .
    

In this example, SET DATABASE provides a hard-coded database file name for preprocessing with gpre. When a user runs the program, the database specified in the variable, fname, is used instead.

Advance To: