Yurttas/PL/DBL/oracle/F/03/PC/q03.pc

From ZCubes Wiki
Jump to navigation Jump to search
  1/*  
  2REM
  3REM q03.pc
  4REM
  5REM Find the model number and price of all products
  6REM (of any type) made by manufacturer 'B'.
  7REM
  8*/
  9
 10#include <stdio.h>
 11#include <sqlca.h>
 12
 13#define UNAME_LEN 32
 14#define PWD_LEN   16
 15
 16VARCHAR username[UNAME_LEN]; /* VARCHAR is an Oracle-supplied struct */
 17VARCHAR password[PWD_LEN];   /* varchar can be in lower case also. */
 18
 19char u_name[UNAME_LEN];
 20char pwd[PWD_LEN];
 21
 22struct {
 23  char model[6];
 24  int price;
 25} modelprice;
 26
 27void connect_to_oracle();
 28void sql_error();
 29
 30void main(int argc, char* argv[]) {
 31  connect_to_oracle();
 32
 33  EXEC SQL DECLARE c CURSOR FOR
 34    (SELECT PC.model, price
 35     FROM Product P, PC
 36     WHERE maker='B'
 37       AND P.model=PC.model )
 38    UNION
 39    (SELECT L.model, L.price
 40     FROM Product P, Laptop L
 41     WHERE maker='B'
 42       AND P.model=L.model)
 43    UNION
 44    (SELECT R.model, R.price
 45     FROM Product P, Printer R
 46     WHERE P.maker='B'
 47       AND P.model=R.model);
 48
 49  EXEC SQL OPEN c;
 50
 51  EXEC SQL WHENEVER NOT FOUND DO BREAK;
 52
 53  printf("\nmodel\tprice\n");
 54  for(;;) {
 55    EXEC SQL FETCH c INTO :modelprice;
 56    printf("%s\t%d\n", modelprice.model,
 57                       modelprice.price);
 58  }
 59
 60  EXEC SQL CLOSE c;
 61
 62  EXEC SQL COMMIT WORK RELEASE;
 63
 64  exit(0);
 65}
 66
 67
 68void sql_error(char* msg) {
 69  char err_msg[128];
 70  int buflen, msglen;
 71
 72  EXEC SQL WHENEVER SQLERROR CONTINUE;
 73
 74  printf("%s \n", msg);
 75  buflen = sizeof(err_msg);
 76  sqlglm(err_msg, &buflen, &msglen);
 77  printf("%.*s \n", msglen, err_msg);
 78  exit(1);
 79}
 80
 81
 82void connect_to_oracle() {
 83  /* get your username/passwd from "user_pwd.txt" file */
 84
 85  FILE *in_file;
 86  in_file = fopen("user_pwd.txt", "r");
 87  fscanf(in_file, "%s", u_name);
 88  fscanf(in_file, "%s", pwd);
 89
 90  strncpy((char *) username.arr, u_name, UNAME_LEN);
 91  username.len = strlen((char *) username.arr);
 92
 93  strncpy((char *) password.arr, pwd, PWD_LEN);
 94  password.len = strlen((char *) password.arr);
 95
 96  EXEC SQL WHENEVER SQLERROR DO sql_error ("ORACLE error-- ");
 97  EXEC SQL CONNECT :username IDENTIFIED BY :password;
 98
 99  printf("connected to oracle - \n");
100}