pro*C访问DB2数据库的例子
test.sqc
$ cat test.sqc
#include
#include
EXEC SQL INCLUDE SQLCA ;
EXEC SQL BEGIN DECLARE SECTION ;
char hvalue[16];
EXEC SQL END DECLARE SECTION ;
char sqlcamsg[1025];
#define DUMP_SQLCA() \
{ \
printf("****************** DUMP OF SQLCA ******************\n"); \
printf("SQLCAID: %s\n", sqlca.sqlcaid); \
printf("SQLCABC: %d\n", sqlca.sqlcabc); \
printf("SQLCODE: %d\n", sqlca.sqlcode); \
printf("SQLERRML: %d\n", sqlca.sqlerrml); \
printf("SQLERRMC: %s\n", sqlca.sqlerrmc); \
printf("SQLERRP: %s\n", sqlca.sqlerrp); \
printf("SQLERRD[0]: %d\n", sqlca.sqlerrd[0]); \
printf("SQLERRD[1]: %d\n", sqlca.sqlerrd[1]); \
printf("SQLERRD[2]: %d\n", sqlca.sqlerrd[2]); \
printf("SQLERRD[3]: %d\n", sqlca.sqlerrd[3]); \
printf("SQLERRD[4]: %d\n", sqlca.sqlerrd[4]); \
printf("SQLERRD[5]: %d\n", sqlca.sqlerrd[5]); \
printf("SQLWARN: %s\n", sqlca.sqlwarn); \
printf("SQLSTATE: %s\n", sqlca.sqlstate); \
printf("***************** END OF SQLCA DUMP **************\n"); \
}
#define CHECK_SQL(failure_string) \
{ \
if (sqlca.sqlcode != 0) { \
printf("!!!ERROR: %s\n", failure_string); \
sqlaintp(sqlcamsg, 1024, 0, &sqlca); \
printf("%s\n", sqlcamsg); \
DUMP_SQLCA(); \
goto done; \
} \
}
main (int argc, char *argv[])
{
EXEC SQL CONNECT TO USER USING ;
CHECK_SQL("Connect failed");
EXEC SQL SELECT 'ABCD' into :hvalue FROM SYSIBM.SYSDUMMY1;
CHECK_SQL("Select failed");
printf("Select Result: [%s]\n", hvalue);
done:
EXEC SQL CONNECT RESET;
}
makefile
$ cat makefile
TARGET=test
DB2DIR?=~/sqllib
$(TARGET): $(TARGET).sqc
db2 connect to user using
db2 prep $(TARGET).sqc bindfile
db2 bind $(TARGET).bnd
#db2 list packages
#db2 drop package package-name
gcc -o $(TARGET) -I$(DB2DIR)/include $(TARGET).c -L$(DB2DIR)/lib64 -ldb2
clean:
rm -f $(TARGET) $(TARGET).bnd $(TARGET).c
run
$ make
db2 connect to user using
Database Connection Information
Database server =
SQL authorization ID =
Local database alias =
db2 prep test.sqc bindfile
LINE MESSAGES FOR test.sqc
------ --------------------------------------------------------------------
SQL0060W The "C" precompiler is in progress.
SQL0091W Precompilation or binding was ended with "0"
errors and "0" warnings.
db2 bind test.bnd
LINE MESSAGES FOR test.bnd
------ --------------------------------------------------------------------
SQL0061W The binder is in progress.
SQL0091N Binding was ended with "0" errors and "0" warnings.
#db2 list packages
#db2 drop package package-name
gcc -o test -I${DB2DIR}/include test.c -L${DB2DIR}/lib64 -ldb2
$
$ ./test
Select Result: [ABCD]