blob: a9175cf7fea6b9a9e3a3f60bb351f97909ad7fe0 [file] [log] [blame]
Tang Cheng37650ea2014-10-20 16:14:41 +08001/*
2 * procdemo.pc
3 *
4 * This program connects to ORACLE, declares and opens a cursor,
5 * fetches the names, salaries, and commissions of all
6 * salespeople, displays the results, then closes the cursor.
7 */
8
9#include <stdio.h>
10#include <string.h>
11#include <sqlca.h>
12#include <stdlib.h>
13#include <sqlda.h>
14#include <sqlcpr.h>
15
16#define UNAME_LEN 20
17#define PWD_LEN 11
18
19/*
20 * Use the precompiler typedef'ing capability to create
21 * null-terminated strings for the authentication host
22 * variables. (This isn't really necessary--plain char *'s
23 * would work as well. This is just for illustration.)
24 */
25typedef char asciiz[PWD_LEN];
26
27EXEC SQL TYPE asciiz IS CHARZ(PWD_LEN) REFERENCE;
28asciiz username;
29asciiz password;
30
31struct emp_info
32{
33 asciiz emp_name;
34 float salary;
35 float commission;
36};
37
38void sql_error(msg)
39 char *msg;
40{
41 char err_msg[512];
42 size_t buf_len, msg_len;
43
44 EXEC SQL WHENEVER SQLERROR CONTINUE;
45
46 printf("\n%s\n", msg);
47
48/* Call sqlglm() to get the complete text of the
49 * error message.
50 */
51 buf_len = sizeof (err_msg);
52 sqlglm(err_msg, &buf_len, &msg_len);
53 printf("%.*s\n", msg_len, err_msg);
54
55 EXEC SQL ROLLBACK RELEASE;
56 exit(EXIT_FAILURE);
57}
58
59void main()
60{
61 struct emp_info *emp_rec_ptr;
62
63/* Allocate memory for emp_info struct. */
64 if ((emp_rec_ptr =
65 (struct emp_info *) malloc(sizeof(struct emp_info))) == 0)
66 {
67 fprintf(stderr, "Memory allocation error.\n");
68 exit(EXIT_FAILURE);
69 }
70
71/* Connect to ORACLE. */
72 strcpy(username, "scott");
73 strcpy(password, "tiger");
74
75 EXEC SQL WHENEVER SQLERROR DO sql_error("ORACLE error--");
76
77 EXEC SQL CONNECT :username IDENTIFIED BY :password;
78 printf("\nConnected to ORACLE as user: %s\n", username);
79
80/* Declare the cursor. All static SQL explicit cursors
81 * contain SELECT commands. 'salespeople' is a SQL identifier,
82 * not a (C) host variable.
83 */
84 EXEC SQL DECLARE salespeople CURSOR FOR
85 SELECT ENAME, SAL, COMM
86 FROM EMP
87 WHERE JOB LIKE 'SALES%';
88
89/* Open the cursor. */
90 EXEC SQL OPEN salespeople;
91
92/* Get ready to print results. */
93 printf("\n\nThe company's salespeople are--\n\n");
94 printf("Salesperson Salary Commission\n");
95 printf("----------- ------ ----------\n");
96
97/* Loop, fetching all salesperson's statistics.
98 * Cause the program to break the loop when no more
99 * data can be retrieved on the cursor.
100 */
101 EXEC SQL WHENEVER NOT FOUND DO break;
102
103 for (;;)
104 {
105 EXEC SQL FETCH salespeople INTO :emp_rec_ptr;
106 printf("%s %9.2f %12.2f\n", emp_rec_ptr->emp_name,
107 emp_rec_ptr->salary, emp_rec_ptr->commission);
108 }
109
110/* Close the cursor. */
111 EXEC SQL CLOSE salespeople;
112
113 printf("\nGOOD-BYE!!\n\n");
114
115 EXEC SQL COMMIT WORK RELEASE;
116 exit(EXIT_SUCCESS);
117}
118