How to use ECPG in MSVC
I'm in the early development of a software and I'm trying to figure out how to use ecpg. I've managed to build PostgreSQL 9.0.4 using MSVC 2010开发者_运维知识库 and have successfully built a test program to ensure it works. (http://www.linuxjournal.com/content/accessing-postgresql-cc, except modified for Windows.)
However I don't know how to build, what to "#include" in the source, etc. for ecpg. I've found plenty of syntax examples but nothing in the way of a test program or walk-though. Even something from a previous version (8.4.x) would be of help.
AFAIK first you need embedded SQL C file (with pgc
extension). Simple example:
int main(void)
{
EXEC SQL BEGIN DECLARE SECTION;
int ordinaryInt;
EXEC SQL END DECLARE SECTION;
EXEC SQL CONNECT TO tcp:postgresql://localhost:5432/postgres AS myconnection USER postgres USING '12345';
EXEC SQL INSERT INTO t (value) VALUES ('abcdefgj');
EXEC SQL COMMIT;
EXEC SQL DISCONNECT myconnection;
return 0;
}
Connection string is explained well in doc. After that you need ecpg.exe
, to transform above code into well-known C code:
Before compiling you run the file through the embedded SQL C preprocessor, which converts the SQL statements you used to special function calls. After compiling, you must link with a special library that contains the needed functions.
For example:
"C:\Program Files (x86)\PostgreSQL\9.0\bin\ecpg.exe" -o ecpgTest.c ecpgTest.pgc
Your generated C code looks like this:
/* Processed by ecpg (4.2.1) */
/* These include files are added by the preprocessor */
#include <ecpglib.h>
#include <ecpgerrno.h>
#include <sqlca.h>
/* End of automatic include section */
#line 1 "ecpgTest.pgc"
int main(void)
{
/* exec sql begin declare section */
#line 4 "ecpgTest.pgc"
int ordinaryInt ;
/* exec sql end declare section */
#line 5 "ecpgTest.pgc"
{ ECPGconnect(__LINE__, 0, "tcp:postgresql://localhost:5432/postgres" , "postgres" , "'12345'" , "myconnection", 0); }
#line 7 "ecpgTest.pgc"
{ ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "insert into t ( value ) values ( 'abcdefgj' )", ECPGt_EOIT, ECPGt_EORT);}
#line 9 "ecpgTest.pgc"
{ ECPGtrans(__LINE__, NULL, "commit");}
#line 10 "ecpgTest.pgc"
{ ECPGdisconnect(__LINE__, "myconnection");}
#line 12 "ecpgTest.pgc"
return 0;
}
Add C:\Program Files (x86)\PostgreSQL\9.0\include
path in Additional Include Directories (Configuration Properties → C/C++) and put libecpg.lib
into Additional Dependiences (Linker → Input) probably you need to add C:\Program Files (x86)\PostgreSQL\9.0\lib
path into Additional Library Directiories (Linker → General) and you're ready to go (note that some DLLs are located in C:\Program Files (x86)\PostgreSQL\9.0\bin
).
精彩评论