#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sqlca.h>
void sql_error();
struct info /*结构体*/ { int id; char name[20]; char sex[6]; char tel[12]; };
struct info_ind /* 指示器变量*/ { short id_ind; short name_ind; short sex_ind; short tel_ind; };
int main(int argc,char * argv[]) {
char * user="admin"; /*数据库用户名*/ char * passwd="admin"; /*数据库密码*/ int id=0; /*宿主变量*/ char strname[20]; char strsex[4]; char strtel[11]; struct info myinfo; struct info_ind ind;
EXEC SQL WHENEVER SQLERROR DO sql_error(); EXEC SQL connect :user identified by :passwd; /*连接数据库*/ if (sqlca.sqlcode == 0) printf("connect sucess/n"); else printf("connect fail/n"); EXEC SQL drop table student; /*如果有该表则先干掉,再创表*/ EXEC SQL create table student(stuid int not null,stuname varchar(20) not null,stusex varchar(4),stutel char(11)); /*创表*/
EXEC SQL insert into student values(1,'feng','boy','12589894789'); /*插入数据*/ EXEC SQL insert into student values(2,'wang','girl','07245689145'); EXEC SQL INSERT INTO student VALUES(3,'long','boy','13122514899'); EXEC SQL insert into student values(4,'xiong','girl','13838383388'); EXEC SQL insert into student values(5,'zhang','boy','15858568945'); while (1) { printf("please input the id:"); fscanf(stdin,"%d",&id); /*EXEC SQL select stuname,stusex,stutel into :strname ,:strsex,:strtel from student where stuid=:id; */ /*可以单个插*/ EXEC SQL select stuid,stuname,stusex,stutel into :myinfo indicator :ind from student where stuid =:id; /*可以插入到一个结构体*/ printf("/nthe infomation:%s/n",myinfo.name); printf("%s/n",myinfo.sex); printf("%s/n",myinfo.tel); } EXEC SQL commit work release; /*提交*/ return 0; }
void sql_error() { printf("oracle error/n"); char buf[100]; int buflen,msglen=0; EXEC SQL WHENEVER SQLERROR CONTINUE; EXEC SQL ROLLBACK WORK RELEASE; buflen=sizeof(buf); sqlglm(buf,&buflen,&msglen); printf("%*,s/n",msglen,buf); exit(1); }
关于pro*c文件的注释 ,建议用/* */ ,若要用 //,据说要在 proc 命令行参数后知道 CODE =CPP ,但我试用时,好像不需要,但还是按
标准用 /**/ 来注释吧。
关于 EXEC SQL ***** 的返回值 为 sqlca.sqlcode ,若返回值为0,则该句执行成功,否则不成功
编译:
可以写成 Makefile 也可以写成 shell
我写的shell
myproc.sh:
in=ch2.pc //修改成你的pro*c 文件 out=ch2.c //修改成你要生成的c文件
proc iname=$in oname=$out
cc -I${ORACLE_HOME}/precomp/public $out -o app -L${ORACLE_HOME}/lib –lclntsh
然后运行该shell
再运行生成的 app 可执行文件