代码:xx.pc
/* 功能:演示了Oracle滚动游标变量的使用 定义游标时注意事项: 1. DECLARE CURSOR语句必须是使用游标的第一条语句 2. 游标名称是一个标识符,而不是宿主变量,其长度是可以任意的,但只有前31个字符有效 3. 游标所对应的SELECT语句不能包含INTO子句 4. 游标语句(DECLARE,OPEN,FETCH,CLOSE)必须在同一个预编译单元内 */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sqlca.h> #pragma comment(lib, "orasql10.lib") int connect(); void cursor(); void sql_error(); void main() { EXEC SQL WHENEVER SQLERROR DO sql_error(); // 安装错误处理句柄 if(connect() == 0) { cursor(); EXEC SQL COMMIT RELEASE; // 提交事务,断开连接 } else printf("连接失败\n"); } int connect() // connect to oracle database { char username[10], password[10], server[10]; strcpy(username, "scott"); strcpy(password, "scott"); strcpy(server, "orcl"); EXEC SQL CONNECT :username IDENTIFIED BY :password USING :server; if(sqlca.sqlcode == 0) return 0; else return sqlca.sqlcode; } void sql_error() // print error infomation { printf("%.*s\n", sqlca.sqlerrm.sqlerrml, sqlca.sqlerrm.sqlerrmc); } void cursor() // 游标操作 { int dno; // 定义宿主变量 char name[10]; float salary; // 定义游标变量 sql_cursor emp_cursor; // sql_cursor:是Proc*C/C++的伪类型 printf("请输入部门号:"); scanf("%d", &dno); EXEC SQL ALLOCATE :emp_cursor; // 分配游标变量 EXEC SQL EXECUTE BEGIN OPEN :emp_cursor FOR Select ename, sal from emp where deptno=:dno; END; END-EXEC; EXEC SQL WHENEVER NOT FOUND DO BREAK; // 游标数据提取完毕后退出循环 while(1) { EXEC SQL FETCH :emp_cursor into :name, :salary; printf("name = %s(%d), salary = %4.0f\n", name, strlen(name), salary); } EXEC SQL CLOSE :emp_cursor; // 关闭游标变量 EXEC SQL FREE :emp_cursor; // 释放游标变量 printf("sqlca.sqlerrd[2] = %d\n", sqlca.sqlerrd[2]); // sqlca.sqlerrd[2]存放着Select语句作用的行数 }
另外还需要做一定的设置: