/* a C program with embedded SQL statements file: first.pgc Preprocess it with ecpg ecpg first.pgc -- this should give the C file first.c, which can be compiled. -- link with file libecpg when linking. All needed files are in their expected locations on all j118 machines. (use -lecpg), so: gcc first.c -lecpg Lin Jensen PROBLEMS: '-' in cs-linux null values can cause trouble, see manual section 30.6.4 char and "varchar" are not null terminated, text is, so use a type cast in SQL, and allow one extra byte! ****************************/ #define NO_MORE_TUPLES !(strcmp(sqlca.sqlstate,"02000")) /* This is the SQL standard test */ #include int main (int argc, char* argv[]) { /* Declare variables here that we want to refer to in SQL */ EXEC SQL BEGIN DECLARE SECTION; const char *target = "timetable@cs-linux"; /* need string because ecpg dislikes - in cs-linux*/ char course[10]; varchar title[26]; char prof[16]; char room[7]; char email[13]; int email_ind; /* will be negative if value is null */ char who[12]; EXEC SQL END DECLARE SECTION; /* declare regular C variables here */ int count; EXEC SQL WHENEVER SQLERROR SQLPRINT; /* ask for error messages */ EXEC SQL WHENEVER SQLWARNING SQLPRINT; EXEC SQL CONNECT TO :target USER mickey/MoUsE; /* Let's do a query now */ if (argc<2) { printf ("Usage: %s ROOM\n", argv[0]); exit(1); } strcpy(who, argv[1]); /* some room number from command line */ EXEC SQL DECLARE rowCurs CURSOR FOR SELECT course, title, prof::TEXT, room::text, email::text FROM courses left join profs on (prof=pname) WHERE room = :who; EXEC SQL OPEN rowCurs; printf ("==== LIST of COURSES for room: %s =====\n",who); count = 0; while(1) { EXEC SQL FETCH rowCurs INTO :course, :title, :prof, :room, :email :email_ind; /* could be null, note lack of comma */ if (NO_MORE_TUPLES) break; course[9] = '\0'; /* null terminate char strings */ title.arr[title.len] = '\0'; /* null terminate varchar string */ if (email_ind < 0) strcpy(email,"(null)"); printf ("%s %-25s %s %s email: %s\n",course, title.arr, room, prof, email); /* we want title left justified (-) and padded anyway. note the effect of variable length on prof */ count++; } EXEC SQL CLOSE rowCurs; /* finished with this cursor */ EXEC SQL COMMIT; /* successful end of transaction */ printf ("%d rows selected.\n", count); EXEC SQL DISCONNECT; return 0; } /* end main*/