Chapter 31. ECPG - Embedded SQL in C

Table of Contents

31.1. The Concept
31.2. Connecting to the Database Server
31.3. Closing a Connection
31.4. Running SQL Commands
31.5. Choosing a Connection
31.6. Using Host Variables
31.6.1. Overview
31.6.2. Declare Sections
31.6.3. Different types of host variables
31.6.4. SELECT INTO and FETCH INTO
31.6.5. Indicators
31.7. Dynamic SQL
31.8. pgtypes library
31.8.1. The numeric type
31.8.2. The date type
31.8.3. The timestamp type
31.8.4. The interval type
31.8.5. The decimal type
31.8.6. errno values of pgtypeslib
31.8.7. Special constants of pgtypeslib
31.9. Informix compatibility mode
31.9.1. Additional embedded SQL statements
31.9.2. Additional functions
31.9.3. Additional constants
31.10. Using SQL Descriptor Areas
31.11. Error Handling
31.11.1. Setting Callbacks
31.11.2. sqlca
31.11.3. SQLSTATE vs SQLCODE
31.12. Preprocessor directives
31.12.1. Including files
31.12.2. The #define and #undef directives
31.12.3. ifdef, ifndef, else, elif and endif directives
31.13. Processing Embedded SQL Programs
31.14. Library Functions
31.15. Internals

This chapter describes the embedded SQL package for PostgreSQL. It was written by Linus Tolke () and Michael Meskes (). Originally it was written to work with C. It also works with C++, but it does not recognize all C++ constructs yet.

This documentation is quite incomplete. But since this interface is standardized, additional information can be found in many resources about SQL.

31.1. The Concept

An embedded SQL program consists of code written in an ordinary programming language, in this case C, mixed with SQL commands in specially marked sections. To build the program, the source code is first passed through the embedded SQL preprocessor, which converts it to an ordinary C program, and afterwards it can be processed by a C compiler.

Embedded SQL has advantages over other methods for handling SQL commands from C code. First, it takes care of the tedious passing of information to and from variables in your C program. Second, the SQL code in the program is checked at build time for syntactical correctness. Third, embedded SQL in C is specified in the SQL standard and supported by many other SQL database systems. The PostgreSQL implementation is designed to match this standard as much as possible, and it is usually possible to port embedded SQL programs written for other SQL databases to PostgreSQL with relative ease.

As already stated, programs written for the embedded SQL interface are normal C programs with special code inserted to perform database-related actions. This special code always has the form

EXEC SQL ...;

These statements syntactically take the place of a C statement. Depending on the particular statement, they may appear at the global level or within a function. Embedded SQL statements follow the case-sensitivity rules of normal SQL code, and not those of C.

The following sections explain all the embedded SQL statements.