Using Strings or host-language Variables
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; . . .
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:
- 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 bygpre
during preprocessing. - Prompt the user for a database to open.
- Store the database name entered by the user in a host-language variable.
- 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.