In the past two days, due to project reasons, I had a little bit of confidence and learned how to embed SQL into PostgreSQL in C. I wrote a small example, including connecting to the database and creating tables, for more information, see PostgreSQL8.0 Chinese manual.
You can use a text editor to write data. pgc file, and then use the ecpg in the bin under the PostgreSQL installation directory to put. pgc file generation. c file, and then use the c compiler to generate the corresponding executable program. On windows, I use VC ++. If the header file or lib cannot be found during compilation, the include directory and lib directory under the PostgreSQL installation directory can be introduced.
The following is the code of the. pgc file. The generated. c file is long and will not be written.
Int main (int argc, char * argv [])
{
Exec SQL CONNECT TO servername@192.168.2.5 USER username/password;
Exec SQL INCLUDE SQLCA;
If (sqlca. sqlcode)
{
Printf ("Connect failed \ n"); // connection failed
}
Else
{
Exec SQL BEGIN DECLARE SECTION;
Char ascii [16 + 1]; // on my system, if no 1 is added, garbled characters will appear after printing on the console.
Exec SQL END DECLARE SECTION;
Printf ("Connect success \ n ");
// Create a table
Exec SQL CREATE TABLE foo (number integer, ascii char (16 ));
Exec SQL CREATE UNIQUE INDEX num1 ON foo (number );
Exec SQL COMMIT;
Printf ("Table Created \ n ");
// Insert data
Exec SQL INSERT INTO foo (number, ascii) VALUES (9999, 'doodad ');
Exec SQL COMMIT;
Printf ("Inserted \ n ");
// Query
Exec SQL SELECT ascii INTO: ascii FROM foo WHERE number = 9999;
Printf ("ascii = % s \ n", ascii );
}
Exec SQL DISCONNECT; // close the connection
Return 0;
}