1/*
2REM
3REM q04.pc
4REM
5REM Suppose we want a relation showing customers and the branches
6REM from which they borrow, but do not care about the amount of the
7REM loan, or the loan number.
8REM
9*/
10
11#include <stdio.h>
12#include <sqlca.h>
13
14#define UNAME_LEN 32
15#define PWD_LEN 16
16
17VARCHAR username[UNAME_LEN]; /* VARCHAR is an Oracle-supplied struct */
18VARCHAR password[PWD_LEN]; /* varchar can be in lower case also. */
19
20char u_name[UNAME_LEN];
21char pwd[PWD_LEN];
22
23struct {
24 char branchname[16];
25 char customername[16];
26} borrower;
27
28void connect_to_oracle();
29void sql_error();
30
31void main(int argc, char* argv[]) {
32 connect_to_oracle();
33
34 EXEC SQL DECLARE c CURSOR FOR
35 SELECT branchname, customername
36 FROM Borrower;
37
38 EXEC SQL OPEN c;
39
40 EXEC SQL WHENEVER NOT FOUND DO BREAK;
41
42 printf("\nbranchname\tcustomername\n");
43 for(;;) {
44 EXEC SQL FETCH c INTO :borrower;
45 printf("%s\t%s\n", borrower.branchname,
46 borrower.customername);
47 }
48
49 EXEC SQL CLOSE c;
50
51 EXEC SQL COMMIT WORK RELEASE;
52
53 exit(0);
54}
55
56
57void sql_error(char* msg) {
58 char err_msg[128];
59 int buflen, msglen;
60
61 EXEC SQL WHENEVER SQLERROR CONTINUE;
62
63 printf("%s \n", msg);
64 buflen = sizeof(err_msg);
65 sqlglm(err_msg, &buflen, &msglen);
66 printf("%.*s \n", msglen, err_msg);
67 exit(1);
68}
69
70
71void connect_to_oracle() {
72 /* get your username/passwd from "user_pwd.txt" file */
73
74 FILE *in_file;
75 in_file = fopen("user_pwd.txt", "r");
76 fscanf(in_file, "%s", u_name);
77 fscanf(in_file, "%s", pwd);
78
79 strncpy((char *) username.arr, u_name, UNAME_LEN);
80 username.len = strlen((char *) username.arr);
81
82 strncpy((char *) password.arr, pwd, PWD_LEN);
83 password.len = strlen((char *) password.arr);
84
85 EXEC SQL WHENEVER SQLERROR DO sql_error ("ORACLE error-- ");
86 EXEC SQL CONNECT :username IDENTIFIED BY :password;
87
88 printf("connected to oracle - \n");
89}