以宿主语言C语言为例
exec sql select Sname, Sage into :vSname, :vSage from Student
where Sname=‘张三’ ;
在嵌入式SQL语句中可以出现宿主语言语句所使用的变量:
exec sql select Sname, Sage into :vSname, :vSage from
Student where Sname= :specName;
这些变量需要特殊的声明:
exec sql begin declare section;
char vSname[10], specName[10]=“张三”;
int vSage;
exec sql end declare section;
execsql connecttotarget-server asconnect-name useruser-name;
或
execsql connecttodefault;
execsql connect:user_name identified by :user_pwd;
execsql connecttomydb user:user_name using:user_pwd;
在嵌入式SQL程序执行之后,需要与数据库断开连接
exec sql disconnect connect-name;
或
exec sql disconnect current;
exec sql commit release;
或
exec sql rollback release;
exec sql connect reset;
exec sql disconnect current;
SQL语句在执行过程中,必须有提交和撤消语句才能确认其操作结果
execsql commitwork;
execsql rollbackwork;
示例
检索多行结果,则需使用游标(Cursor)
//定义
exec sql declare cur_student cursor for
select Sno, Sname, Sclass from Student where Sclass=‘035101’ ;
//打开
exec sql open cur_student;
//推进
exec sql fetch cur_student into :vSno, :vSname, :vSclass;
… …
//关闭
exec sql close cur_student;
示例
exec sql declare cur_student cursor for
select Sno, Sname, Sclass from Student where Sclass= :vClass
order by Sno for read only ;
exec sql open cur_student;
…
exec sql fetch cur_student into :vSno, :vSname, :vSage
…
exec sql close cur_student;
一种是查找删除(与交互式DELETE语句相同),一种是定位删除
示例:查找删除
普通SQL语句一样的删除
exec sql delete from customers c where c.city = ‘Harbin’ and
not exists ( select * from orders o where o.cid = c.cid);
示例:定位删除
加current of 游标名
表示删除游标所指的当前内容
exec sql declare delcust cursor for
select cid from customers c where c.city =‘harbin’ and
not exists ( select * from orders o where o.cid = c.cid)
for update of cid;
exec sql open delcust
While (TRUE) {
exec sql fetch delcust into :cust_id;
exec sql delete from customers where current of delcust ; }
一种是查找更新(与交互式Update语句相同),一种是定位更新
示例:查找更新
exec sql update student s set sclass = ‘035102’
where s.sclass = ‘034101’
示例:定位更新
exec sql declare stud cursor for
select * from student s where s.sclass =‘034101’
for update of sclass;
exec sql open stud
While (TRUE) {
exec sql fetch stud into :vSno, :vSname, :vSclass;
exec sql update student set sclass = ‘035102’ where current of
stud ; }
exec sql insert into student ( sno, sname, sclass)
values (‘03510128’, ‘张三’, ‘035101’) ;
示例:插入语句
exec sql insert into masterstudent ( sno, sname, sclass)
select sno, sname, sclass from student;
示例:宿主语言与SQL结合的过程性控制
求数据库中某一列位于中值的那一行
嵌入式 SQL程序中,状态捕获及处理有三部分构成
exec sql include sqlca;
exec sql whenever sqlerror goto report_error;
report_error: exec sql rollback;
状态捕获语句Whenever的作用范围是其后的所有Exec SQL语句,一直到程序中出现另一条相同条件的Whenever语句为止,后面的将覆盖前面的。