/*
** PostgrSQL 数据库 C语言中 嵌入SQL
**
** 使用ECPG程序对此进行编译得到C语言文件,然后再用-lecpg编译连接
** 得到可执行程序。运行的时候需要libecpg.dll文件和libpq.dll等其他库。
** comerr32.dll, krb5_32.dll, libpgtypes.dll, pthreadGC2.dll
*/
#include
#include
EXEC SQL INCLUDE SQLCA;
#define TEST_NO_SQL_ERROR (sqlca.sqlstate[0]=='0' && sqlca.sqlstate[1]=='0' && sqlca.sqlstate[2]=='0' && sqlca.sqlstate[3]=='0' && sqlca.sqlstate[4]=='0')
#define TEST_SQL_ERROR (!TEST_NO_SQL_ERROR)
int main(){
/* 变量的声明 */
EXEC SQL BEGIN DECLARE SECTION;
int nAge;
varchar vcName[80];
EXEC SQL END DECLARE SECTION;
/* 连接数据库 */
EXEC SQL CONNECT TO mydb@localhost USER test;
if (TEST_SQL_ERROR){
puts("连接数据库: Failed!");
puts(sqlca.sqlerrm.sqlerrmc);
exit(-1);
}
puts("连接数据库:OK!");
/* 使用游标来读取多个数据 */
EXEC SQL BEGIN;
EXEC SQL DECLARE CURPP CURSOR FOR select name, age from tb_people;
EXEC SQL OPEN CURPP;
while(TEST_NO_SQL_ERROR){
EXEC SQL FETCH NEXT FROM CURPP INTO :vcName, :nAge;
if (TEST_NO_SQL_ERROR){
printf("%s is %d old.\n", vcName.arr, nAge);
}else{
puts(sqlca.sqlerrm.sqlerrmc);
break;
}
}
EXEC SQL CLOSE CURPP;
EXEC SQL COMMIT;
/* 断开连接 */
EXEC SQL DISCONNECT;
return 0;
}