Chapter 3. ecpg - Embedded SQL in C

Embedded SQL is a specialized language intended for use within programs that are written in other languages and that need to interact with databases.

Embedded SQL is an ANSI standard that many database management systems (DBMS) support. Red Hat Database supports the Embedded SQL in C standard as much as possible to facilitate the porting of C programs using this standard.

The basic idea behind Embedded SQL is that you write a program in a host language, which must be C in the case of Red Hat Database, and embed SQL statements in it using Embedded SQL. Before the program can be compiled, it must be run through the Embedded SQL preprocessor, which converts all Embedded SQL code to library calls. The resulting C program is then compiled. When linking, you must link with the Embedded SQL library in addition to libpq and regular libraries.

Using ecpg

The ecpg facility includes a preprocessor called ecpg, along with header files and libraries. All of these can be found in the rh-postgresql-devel package. Refer to the Red Hat Database Getting Started / Installation Guide for details on installing the rh-postgresql-devel package.

The ecpg preprocessor should be run on all C programs that contain Embedded SQL. ecpg's usage is:

ecpg [options] file1 [file2] [file3] ...

The following command-line options are recognized:

OptionDescription
-vPrint version information.
-tTurn on auto-transaction mode. By default, SQL statements are not committed or rolled back until either a COMMIT or a ROLLBACK is executed. If auto-transaction mode is turned on, every SQL statement is run in its own transaction.
-I pathSpecify an additional include path. Defaults are the current directory (.), /usr/local/include, /usr/include/pgsql, and /usr/include.
-o outSpecify that ecpg should write all of its output to the file out. If the -o option is not given, the output is written to name.c, where name.extension is the input file.

Example:

$ ecpg foo.pgc
$ ls
foo.c        foo.pgc
$

After preprocessing, you need to compile and link. Programs using Embedded SQL need to be linked against two libraries: libecpg and libpq. An example compile command is:

$ gcc -g -I/usr/include/pgsql foo.c -o foo -lecpq -lpq

The ecpg library includes utility functions that can be useful in some situations. They are normal C functions that are not embedded in any way.