In the three previous chapters, you've seen how to connect a C or C++ application to a PostgreSQL database by making function calls into a PostgreSQL API. Now you're going to look at a different method for interfacing C applications with PostgreSQL. The ecpg preprocessor and runtime library enable you to embed SQL commands directly into the source code of your application. Rather than making explicit function calls into PostgreSQL, you include specially tagged SQL statements in your C code. The ecpg preprocessor examines your source code and translates the SQL statements into the function calls needed to carry out the operations that you request. When you run the ecpg preprocessor, you feed it a source file that includes both C source code and SQL commands; the preprocessor produces a file that contains only C source code (it translates your SQL commands into function calls) and you then compile the new C file. Using ecpg, you can retrieve PostgreSQL data directly into C variables, and the ecpg runtime library takes care of converting between PostgreSQL data types and C data types.
The ecpg package is great for developing static applications?applications whose SQL requirements are known at the time you write your source code. ecpg can also be used to process dynamic SQL. Dynamic SQL is an accepted standard (part of the ANSI SQL3/SQL99 specification) for executing SQL statements that may not be known until the application is actually executing. I'll cover the dynamic SQL features at the end of this chapter, but I don't think that ecpg offers many advantages (over libpq) when dealing with ad hoc queries.