teststu.cp
#include <stdio.h> /*建立通訊區域*/ EXEC SQL INCLUDE SQLCA; /* ** These tokens must be declared in a declare section ** because they are used in declare sections below. */ EXEC SQL BEGIN DECLARE SECTION; #define TYPESIZE 13 #define TIDSIZE 6 EXEC SQL END DECLARE SECTION; #define EOLN '\0' /* ** Forward declarations of the error and message handlers and ** other subroutines called from main(). */ void error_handler(); void warning_handler(); int main(int argc, char *argv[]) { /*聲明宿主變量*/ EXEC SQL BEGIN DECLARE SECTION; /* storage for login name and password. */ char username[30]; char sname[30]; char password[30]; char server[30]; EXEC SQL END DECLARE SECTION; /*錯誤處理*/ EXEC SQL WHENEVER SQLERROR CALL error_handler(); EXEC SQL WHENEVER SQLWARNING CALL warning_handler(); EXEC SQL WHENEVER NOT FOUND CONTINUE; /*連接到 SQL SERVER 服務器*/ strcpy(username, "mymotif"); strcpy(password, "wxwpxh"); strcpy(server, "MYMOTIFVOSTRO145480"); EXEC SQL CONNECT :username IDENTIFIED BY :passWord using :server; /*執行查詢,並顯示結果*/ EXEC SQL USE testdb; EXEC SQL DECLARE c1 CURSOR FOR SELECT SNAME FROM STUDENT; EXEC SQL OPEN c1; printf("name in table student\n"); do { EXEC SQL FETCH c1 INTO :sname; if (sqlca.sqlcode != 0) break; printf( "student name = %s\n", sname ); } while ( 1 ); EXEC SQL CLOSE c1; return(0); } /*錯誤處理程序*/ /* ** void error_handler() ** ** Displays error codes and numbers from the SQLCA and exits with ** an ERREXIT status. */ void error_handler(void) { fprintf(stderr, "\n** SQLCODE=(%ld)", sqlca.sqlcode); if (sqlca.sqlerrm.sqlerrml) { fprintf(stderr, "\n** ASE Error "); fprintf(stderr, "\n** %s", sqlca.sqlerrm.sqlerrmc); } fprintf(stderr, "\n\n"); exit(-1); } /* ** void warning_handler() ** ** Displays warning messages. */ void warning_handler(void) { if (sqlca.sqlwarn[1] == 'W') { fprintf(stderr, "\n** Data truncated.\n"); } if (sqlca.sqlwarn[3] == 'W') { fprintf(stderr, "\n** InsufficIEnt host variables to store results.\n"); } return; }
編譯:
$cpre64 -m teststu.cp $ cc -m64 -g -DSYB_LP64 -I. -I/opt/sybase/OCS-16_0/include teststu.c /opt/sybase/OCS-16_0/include/sybesql.c -L/opt/Sybase/OCS-16_0/lib -lsybct64 -lsybtcl64 -lsybcs64 -lsybcomn64 -lsybintl64 -lsybunic64 -rdynamic -ldl -lnsl -lm -o teststu
執行:
$ ./teststu name in table student student name = 馬志元 student name = 馬元 student name = 王海濱 student name = 金力標 student name = 馬小樂 student name = 馬娟