db2 declare cursor for会锁表么

DB2中可以读写的游标的定义,DB2教程,DB2案例,DB2实例
     本站短域名:珠江路.cn、zjlu.net
        
     
 |  | 
          
您的位置: &&
&& DB2中可以读写的游标的定义
DB2中可以读写的游标的定义
  本文标签:  
  导读:中是非常重要的一个,游标提供了一种对从表中检索出的进行的灵活手段,就本质而言,游标实际上是一种能从包括多条数据的结果集中每次提取一条记录的&&。
  使用操作更改行
可游标通过游标更新行的数据&&。当定位在可更新游标中的某行上时,您可以更 新或操作,这些操作针对用于在游标中建立当前行的基表行&&。 这些就称为定位更新&&。 定位更新在打开游标的同一个上执行&&。 这就允许数据修改共享与游标相同的空间,并且使游标保持的锁不会阻止更新&&。
有两种在游标中执行定位更新:
UTE 或 DELETE 语句中的 -SQL WHERE CURRENT OF 子句&&。
I 定位更新或方法,如
SQLSetPos 函数&&。
使用 Transact-SQL 执行定位更新
Transact-SQL WHERE CURRENT OF 子句典型用于 Transact-SQL 过程、以及
(当需要根据游标中特定行进行修改时)&&。、触发器、或脚本将:
DECLARE 和 OPEN 游标&&。
用 FETCH 语句在游标中定位于一行&&。
用 WHERE CURRENT OF 子句执行
或 DELETE 语句&&。用 DECLARE 语句中的 cursor_
作为 WHERE CURRENT OF 子句中的 cursor_name&&。
declare cursor_name cursor for
open cursor_name
fetch next from cursor_name
while @@Fetch_Status = 0
sname = lx_ + sname --right(sname,len(sname)-3)
current of cursor_name
fetch next from cursor_name
close cursor_name
deallocate Cursor_Name
  在DB2中也有类似的,由于DB2中的SQL和SQL RVER有所不同,所以DB下的存储过程如下:
CREATE PRORE KYJT.SP_TESTT ( )
IFIC KYJT.SQL193
NOT DETERMINTIC
MODIFS SQL DATA
INHER SPECIAL REGISTERS
DECLARE PE VAHAR(50);
DECLARE PID INT;
DECLARE v_
DECLARE SQLSTATE CHAR(5);
DECLARE at_end INT DEFAULT 0;
DECLARE not_found CONDIT
SQLSTATE 0;
  DECLARE C1 CURSOR FOR SELECT ID,NA F KYJT.TESTT FOR UPDATE ;
DECLARE CONTINUE HANDLER FOR not_found
SET at_end = 1;
FETCH C1 INTO PID,PNAME;
if at_end = 1 n
LEAVE INS_LOOP;
UPDATE KYJT.TESTT A
SET NAME = (SELECT NAME FROM KYJT.TEST B WHERE B.ID=PID) WHERE CURRENT OF C1;
数据库开发
产品库推荐
All Rights Reserved.
珠江路在线版权所有
 |  |  | The DECLARE CURSOR statement defines a cursor.
This statement can only be embedded in an application program.
It is not an executable statement.
No authorization is required to use this statement. However to
use OPEN or FETCH for the cursor, the privileges held by the authorization ID
of the statement must include at least one of the following:
For each table or view identified in the SELECT statement of the
The SELECT privilege on the table or view, and
The system authority *EXECUTE on the library containing the table or view
Administrative authority
The authorization ID of the statement has the SELECT privilege on a table
It is the owner of the table,
It has been granted the SELECT privilege on the table, or
It has been granted the system authorities of *OBJOPR and *READ on the
The authorization ID of the statement has the SELECT privilege on a view
It is the owner of the view,
It has been granted the SELECT privilege on the view, or
It has been granted the system authorities of *OBJOPR and *READ on the
view and the system authority *READ on all tables and views that this view is
directly or indirectly dependent on. That is, all tables and views
referenced in the view definition, and if a view is referenced, all tables and
views referenced in its definition, and so forth.
The SELECT statement of the cursor is one of the following:
The prepared select-statement identified by the
statement-name.
The specified select-statement.
If statement-name is specified:
The authorization ID of the statement is the run-time authorization ID
unless DYNUSRPRF(*OWNER) was specified on the CRTSQLxxx command when the
program was created. For more information, see .
The authorization check is performed when the select-statement is prepared
unless DLYPRP(*YES) is specified on the CRTSQLxxx command.
The authorization check is performed when the cursor is opened for
programs compiled with the DLYPRP(*YES) parameter.
If the select-statement is specified:
If USRPRF(*OWNER) or USRPRF(*NAMING) with SQL naming was specified on the
CRTSQLxxx command, the authorization ID of the statement is the owner of the
SQL program or package.
If USRPRF(*USER) or USRPRF(*NAMING) with system naming was specified on
the CRTSQLxxx command, the authorization ID of the statement is the run-time
authorization ID.
In REXX, the authorization ID of the statement is the run-time
authorization ID.
The authorization check is performed when the cursor is opened.
>>-DECLARE--cursor-name----+--------------+--------------------->
'-INSENSITIVE--'
>-----+------------------------+--CURSOR--+-----------+--FOR---->
'-+----------+---SCROLL--'
'-WITH HOLD-'
'-DYNAMIC--'
>-----+-select-statement-+------------------------------------->&
'-statement-name---'
cursor-name
Names a cursor. The name must not be the same as the name of
another cursor declared in your source program.
INSENSITIVE
Specifies that once the cursor is opened, it does not have sensitivity to
inserts, updates, or deletes performed by this or any other activation
group. If INSENSITIVE is specified, the cursor is read-only and a
temporary result is created when the cursor is opened. In addition, the
SELECT statement cannot contain a FOR UPDATE clause and the application must
allow a copy of the data (ALWCPYDTA(*OPTIMIZE) or ALWCPYDTA(*YES)).
Specifies that the cursor is scrollable. The cursor may or may not
have immediate sensitivity to inserts, updates, and deletes done by other
activation groups. If DYNAMIC is not specified, the cursor is
read-only. In addition, the SELECT statement cannot contain a FOR
UPDATE clause.
DYNAMIC SCROLL
Specifies that the cursor is updateable if the result table is updateable,
and that the cursor will usually have immediate sensitivity to inserts,
updates, and deletes done by other application processes. However, in
the following cases, the keyword DYNAMIC is ignored and the cursor will not
have immediate sensitivity to the inserts, updates, and deletes:
Queries that are implemented as temporary result tables. A
temporary result table is created when:
The total length in bytes of storage for the columns specified in an ORDER
BY clause exceeds 2000 bytes.
The ORDER BY and GROUP BY clauses specify different columns or columns in
a different order.
The ORDER BY and GROUP BY clauses include a user-defined function or one
of the following scalar functions: DLVALUE, DLURLPATH, DLURLPATHONLY,
DLURLSERVER, DLURLSCHEME, or DLURLCOMPLETE for DataLinks with an attribute of
FILE LINK CONTROL and READ PERMISSION DB.
The UNION or DISTINCT clauses are specified.
The ORDER BY or GROUP BY clauses specify columns which are not all from
the same table.
A logical file defined by the JOINDFT data definition specifications (DDS)
keyword is joined to another file.
A logical file that is based on multiple database file members is
specified.
The CURRENT or RELATIVE scroll options are specified on the FETCH
statement when the select statement of the DECLARE CURSOR contains a GROUP BY
Queries that include a subquery where:
The outermost query does not provide correlated values to any inner
subselects.
No IN, = ANY, = SOME, or &> ALL subqueries are referenced by the
outermost query.
Prevents the cursor from being closed as a consequence of a commit
operation. A cursor declared using the WITH HOLD clause is implicitly
closed at commit time only if the connection associated with the cursor is
ended during the commit operation.
When WITH HOLD is specified, a commit operation commits all the changes in
the current unit of work, but releases only locks that are not required to
maintain the cursor. Afterwards, a FETCH statement is required before a
Positioned UPDATE or DELETE statement can be executed.
All cursors are implicitly closed by a CONNECT (Type 1) or rollback
operation. All cursors associated with a connection are implicitly
closed by a disconnect of the connection. A cursor is also implicitly
closed by a commit operation if WITH HOLD is not specified, or if the
connection associated with the cursor is in the release-pending state.
If a cursor is closed before the commit operation, the effect is the same
as if the cursor was declared without the WITH HOLD option.
select-statement
Specifies the SELECT statement of the cursor. See
for more information.
The select-statement must not include parameter markers (except
for REXX), but can include references to host variables. In host
languages, other than RPG, PL/I, and REXX, the declarations of the host
variables must precede the DECLARE CURSOR statement in the source
program. Host variable declarations can follow the DECLARE CURSOR
statement in RPG and PL/I. In REXX, parameter markers must be used in
place of host variables and the statement must be prepared.
statement-name
The SELECT statement of the cursor is the prepared select-statement
identified by the statement-name when the cursor is opened.
The statement-name must not be identical to a statement-name
specified in another DECLARE CURSOR statement of the source program.
for an explanation of prepared statements.
The DECLARE CURSOR statement must precede all statements that explicitly
reference the cursor by name.
A cursor in the open state designates a result table and a
position relative to the rows of that table. The table is the result
table specified by the SELECT statement of the cursor.
The result table is read-only if any of the following are
The first FROM clause identifies more than one table or view.
The first FROM clause identifies a read-only view.
The first SELECT clause specifies the keyword DISTINCT.
The outer subselect contains a GROUP BY clause.
The outer subselect contains a HAVING clause.
The first SELECT clause contains a column function.
The select-statement contains a UNION or UNION ALL operator.
The select-statement contains an ORDER BY clause, and the FOR UPDATE OF
clause and DYNAMIC SCROLL are not specified.
The select-statement includes a FOR FETCH ONLY clause.
The SCROLL keyword is specified without DYNAMIC.
The select list includes a DATALINK column and a FOR UPDATE OF clause is
not specified.
The first subselect requires a temporary result table.
Cursors whose result tables are not read-only may be updated.
The scope of cursor-name is the source program in which it is
defined, that is, the program submitted to the precompiler. Thus, you
can only reference a cursor by statements that are precompiled with the cursor
declaration. For example, a program called from another separately
compiled program cannot use a cursor that was opened by the calling
The scope of cursor-name is also limited to the thread in which the program
that contains the cursor is running. For example, if the same program
is running in two separate threads in the same job, the second thread cannot
use a cursor that was opened by the first thread.
A cursor can only be referred to in the same instance of the program in the
program stack unless CLOSQLCSR(*ENDJOB), CLOSQLCSR(*ENDSQL), or
CLOSQLCSR(*ENDACTGRP) is specified on the CRTSQLxxx commands.
If CLOSQLCSR(*ENDJOB) is specified, the cursor can be referred to by any
instance of the program on the program stack.
If CLOSQLCSR(*ENDSQL) is specified, the cursor can be referred to by any
instance of the program on the program stack until the last SQL program on the
program stack ends.
If CLOSQLCSR(*ENDACTGRP) is specified, the cursor can be referred to by
all instances of the module in the activation group until the activation group
Although the scope of a cursor is the program in which it is declared, each
package created from the program includes a separate instance of the cursor
and more than one cursor can exist at run time. For example, assume a
program using CONNECT (Type 2) statements connects to location X and location
Y in the following sequence:
EXEC SQL DECLARE C CURSOR FOR...
EXEC SQL CONNECT TO X;
EXEC SQL OPEN C;
EXEC SQL FETCH C INTO...
EXEC SQL CONNECT TO Y;
EXEC SQL OPEN C;
EXEC SQL FETCH C INTO...
The second OPEN C statement does not cause an error because it refers to a
different instance of cursor C.
The ALWCPYDTA precompile option is ignored for DYNAMIC SCROLL
cursors. If sensitivity to inserts, updates, and deletes must be
maintained, a temporary copy of the data is never made unless a temporary
result is required to implement the query.
A SELECT statement is evaluated at the time the cursor is opened. If
the same cursor is opened, closed, and then opened again, the results may be
different. Multiple cursors using the same SELECT statement can be
opened concurrently. They are each considered independent
activities.
If ORDER BY is specified and FOR UPDATE OF is specified, the columns in the
FOR UPDATE OF clause cannot be the same as any columns specified in the ORDER
BY clause.
If the FOR UPDATE OF clause is omitted, only the columns in the SELECT
clause of the subselect that can be updated can be changed.
If host variables are used on the DECLARE CURSOR statement within a REXX
procedure, then the DECLARE CURSOR must be the object of a PREPARE and
In a PL/I program, use the cursor C1 to fetch the values for a given
project (PROJNO) from the first four columns of the EMP_ACT table a row at
a time and put them into the following host variables: EMP (char(6)),
PRJ (char(6)), ACT (smallint), and TIM (dec(5,2)). Obtain the value of
the project to search for from the host variable SEARCH_PRJ
(char(6)).
BEGIN DECLARE SECTION;
SEARCH_PRJ
BINARY FIXED(15);
FIXED(5,2);
END DECLARE SECTION;
DECLARE C1 CURSOR FOR
SELECT EMPNO, PROJNO, ACTNO, EMPTIME
FROM EMP_ACT
WHERE PROJNO = :SEARCH_PRJ;
FETCH C1 INTO :EMP, :PRJ, :ACT, :TIM;
IF SQLSTATE = '02000' THEN
CALL DATA_NOT_FOUND;
DO WHILE (SUBSTR(SQLSTATE,1,2) = '00'
| SUBSTR(SQLSTATE,1,2) = '01');
FETCH C1 INTO :EMP, :PRJ, :ACT, :TIM;
In a PL/I program, declare a cursor named INCREASE to return from the
EMPLOYEE table all the employee numbers (EMPNO), surnames (LASTNAME) and price
(SALARY increased by 10 percent) of people who have the job of clerk
(JOB). Order the result table in descending order by the increased
DECLARE INCREASE CURSOR FOR
SELECT EMPNO, LASTNAME, SALARY * 1.1
FROM EMPLOYEE
WHERE JOB = 'CLERK'
ORDER BY 3 DESC;
In a PL/I program, declare a cursor named UP_CUR to update all the
columns of the DEPARTMENT table.
DECLARE UP_CUR CURSOR FOR
FROM DEPARTMENT
FOR UPDATE OF DEPTNO, DEPTNAME, MGRNO, ADMRDEPT;
In a PL/I program, declare a cursor named DEL_CUR to examine, and
potentially delete, rows in the DEPARTMENT table.
DECLARE DEL_CUR CURSOR FOR
FROM DEPARTMENT;
This example is similar to Example 1. The difference is that the
right-hand side of the WHERE clause is to be s thus
the entire select-statement is placed into a host variable and dynamically
BEGIN DECLARE SECTION;
SEARCH_PRJ
FIXED(15);
FIXED(5,2);
SELECT_STMT
END DECLARE SECTION;
SELECT_STMT = 'SELECT EMPNO, PROJNO, ACTNO, EMPTIME ' ||
'FROM EMP_ACT ' ||
'WHERE PROJNO = ?';
PREPARE SELECT_PRJ FROM :SELECT_STMT;
DECLARE C1 CURSOR FOR SELECT_PRJ;
OPEN C1 USING :SEARCH_PRJ;
FETCH C1 INTO :EMP, :PRJ, :ACT, :TIM;
IF SQLSTATE = '02000' THEN
CALL DATA_NOT_FOUND;
DO WHILE (SUBSTR(SQLSTATE,1,2) = '00'
| SUBSTR(SQLSTATE,1,2) = '01');
FETCH C1 INTO :EMP, :PRJ, :ACT, :TIM;
The DECLARE CURSOR statement associates the cursor name C1 with the
results of the SELECT. C1 is an updateable, scrollable cursor.
EXEC SQL DECLARE C1 DYNAMIC SCROLL CURSOR FOR
SELECT DEPTNO, DEPTNAME, MGRNO
FROM CORPDATA.TDEPT
WHERE ADMRDEPT = 'A00';
Declare a cursor in order to fetch values from four columns and assign
the values to host variables using the Serializable (RR) isolation
DECLARE CURSOR1 CURSOR FOR
SELECT COL1, COL2, COL3, COL4
FROM TBLNAME WHERE COL1 = :varnameoracle中pro*c的学习-oracle-电脑编程网oracle中pro*c的学习作者:unirong 和相关&& 一 pro*c 程序概述:1.什么是pro*c程序在管理和系统中, 有三种访问的方法;(1) 用sql*plus, 它有sql命令以交互的应用程序访问数据库;(2) 用第四代语言应用开发工具开发的应用程序访问数据库,这些工具有sql*froms,ql*reportwriter,sql*menu等;(3) 利用在第三代语言内嵌入的sql语言或库函数调用来访问。pro*c就属于第三种开发工具之一, 它把过程化语言c和非过程化语言sql最完善地结合起来, 具有完备的过程处理能力,又能完成任何数据库的处理品任务,使用户可以通过编程完成各种类型的报表。在pro*c程序中可以嵌入sql语言, 利用这些sql语言可以完成动态地建立、修改和删除数据库中的表,也可以查询、插入、修改和删除数据库表中的行, 还可以实现事务的提交和回滚。在pro*c程序中还可以嵌入pl/sql块, 以改进应用程序的性能, 特别是在网络环境下,可以减少网络传输和处理的总开销。 2.pro*c的程序结构图通俗来说,pro*c程序实际是内嵌有sql语句或pl/sql块的c程序, 因此它的组成很类似c程序。 但因为它内嵌有sql语句或pl/sql块, 所以它还含有与之不同的成份。为了让大家对pro*c有个感性的认识, 特将二者差别比较如下:c的全程变量说明c源程序 函数1:同函数k。函数2:同函数k。 c的局部变量说明函数k 可执行语句应用程序首部 c的外部变量说明外部说明段(oracle变量说明)通讯区说明pro*c源程序 函数1:同函数k。函数2:同函数k。c局部变量说明程序体 内部说明部分 内部说明段通讯区说明函数k c的可执行语句 可执行语句 sql的可执行语句 或pl/sql块二.pro*c程序的组成结构每一个pro*c程序都包括两部分:(1)应用程序首部;(2)应用程序体应用程序首部定义了oracle数据库的有关变量, 为在c语言中操纵oracle数据库做好了准备。应用程序体基本上由pro*c的sql语句调用组成。主要指查询select、insert、update、delete等语句。应用程序的组成结构如图所示: exec sql begin declare section (sql变量的定义)exec sql end declare section;exec sql include sqlla;exec sql connect:& 用户名& identified by: & 口令 &sql 语句及游标的使用1. 应用程序首部应用程序的首部就是pro*c的开始部分。它包括以下三部分:l c变量描述部分;l sql变量描述部分(declare部分);l sql通信区。(1) .declare部分(描述部分)描述部分说明程序的sql变量, 定义部分以exec sql be开始和以 exec sql end declare section ;结束的。它可以出现在程序的主部,也可出现在局部l sql变量的说明和使用在说明段能为sql变量指定的数据类型如表所示:数据类型 描述charchar(n)int short long float double varchar 单字符n个字符数组整数短整数单精度浮点数双精度浮点数变长字符串这些数据类型实际上就是c语言的数据类型, 其中varchar中视为c数据类型的扩充。这在以后会谈到。sql变量的使用应注意以下几点:l 必须在描述部分明确定义l 必须使用与其定义相同的大小写格式l 在sql语句中使用时,必须在其之前加一个&:&(冒号),但在c语句中引用时不需加冒号。l 不能是sql命令中的保留字。l 可以带指示变量。例如:exec sql bevarchar programe[30];int porgsal,exec sqlexec sql select ename , sal into: programe, : progsal from emp where empno = :(2). 指示器变量的说明和引用指示变量实际上也是一类sql变量,它被用来管理与其相关联的宿主变量(即在sql语句中充 当输入或输出的变量)。每一个宿主变量都可定义一个指示器变量,主要用于处理空值(null)指示器变量的说明基本同一般sql变量一样, 但必须定义成2字节的整型,如short、int。在sql语句中引用时, 其前也应加&:&(冒号),而且必须附在其相关联的宿主变量之后,在c语句中,可独立使用。当指示器变量为-1时,表示空值。例如:exec sql be int dept-short ind &char emp &exec sql
scanf(&90d %s&, & dept- number , dept & name );if (dept & number ==0)ind & num = -1;else ind & num = 0;exec sql insert into dept (deptno, dname)values(:dept & number : ind- num , :dept & name);其中ind & num是dept & number 的指示器变量。当输入的dept & number 值是0时, 则向dept 表的deptno列插入空值。(3).指针sql变量的说明和使用指针sql变量在引用前也必须在declare 部分先说明。其说明格式同c语言。在sql语句中引用时,指针名字前要加前缀&:&(冒号)而不加&*&(星号)。在c语句中用法如同c语言的指针变量。(4).数组sql变更的说明和引用在sql语句中引用数组时,只需写数组名(名字前加冒号), 不需写下标,在c语句中用法如同c语言的数组变量。使用数组可大大降低网络传输开销。如要向一表插入100行数据,如果没有数组,就要重复100次, 而引用后,只须执行一次insert语句、便可一次性插入。例如:exec sql bint emp_number[100];char emp_name[100][15];float salary[100],commission[100];int dept_exec sql&.exec sql select empno,ename,sal,comminto :emp_number,:emp_name,:salary,:commissionfrom empwhere deptno=:dept_在使用数组时,应注意以下几点;l 不支持指针数组l 只支持一维数组, 而 emp-name [100][15]视为一维字符串l 数组最大维数为32767l 在一条sql语句中引用多个数组时,这些数组维数应相同l 在values , set, into 或where子名中, 不允许把简单sql变量与数组sql变量混用l 不能在delare部分初始化数组例如:下面的引用是非法的exec sql bint dept & num [3] = ;exec sql exec sql select empno, ename , salinto : emp & num [ i ], : emp & name [ i ], : salarg [ i ]from emp (5) 伪类型varchar的说明和引用varchar变量在引用之前也必须在说明段说明, 说明时必须指出串的最大 长度,如:exec sql begin declare section;int book & varchar book & name [ 50 ];exec sql
在预编绎时, book & name 被翻译成c语言中的一个结构变量;struct {unsigned chart arr [ 20 ] ; } boo & name 由此看出, varchar变量实际上是含长度成员和数组成员的结构变量。在sql语句中引用时,应引用以冒号为前缀的结构名, 而不加下标,在c语句 中引用结构成员。varchar变量在作输出变量时,由oracle自动设置, 在作为输入变量时,程序应先把字符串存入数组成员中, 其长度存入长度成员中,然后再在sql语句中引用。例如:main( ){ .......scanf(&90s, 90d&, book & name .arr, & book & number );book & name .len = strlen (book & name .arr);exec sql update book set bname = : book &bdesc = : book &} (6) sql通信区sql 通信区是用下列语句描述的:exec sql include sqlca;此部分提供了用户运行程序的成败记录和错误处理。sqlca的组成sqlca是一个结构类型的变量,它是oracle 和应用程序的一个接口。在执行 pro*c程序时, oracle 把每一个嵌入sql语句执行的状态信息存入sqlca中, 根据这些信息,可判断sql语句的执行是否成功,处理的行数,错误信息等,其组成如表所示:struct sqlca{ char sqlcaid [ 8 ] ; ----&标识通讯区 ---& 通讯区的长度 ---&保留最近执行的sql语句的状态码struct { uns -----&信息文本长度}char sqlerrp [ 8 ];long sqlerrd [ 6 ];char sqlwarn [ 8 ];char sqlext [ 8 ];}其中, sqlcode在程序中最常用到,它保留了最近执行的sql语句的状态码。程序员根据这些状态码做出相应的处理。这些状态码值如下:0: 表示该sql语句被正确执行,没有发生错误和例外。&0:oracle执行了该语句,但遇到一个例外(如没找到任何数据)。&0:表示由于数据库、系统、网络或应用程序的错误,oracle未执行该sql语句。 当出现此类错误时,当前事务一般应回滚。 2.应用程序体在pro*c程序中, 能把sql语句和c语句自由地混合书写,并能在sql语句中使用sql变量,嵌入式sql语句的书写文法是:l 以关键字exec sql开始l 以c语言的语句终结符(分号)终结sql语句的作用主要用于同数据库打交道。c语言程序用于控制,输入,输出和数据处理等。(1) 连接到oracle数据库在对数据库存取之前,必须先把程序与oracle数据库连接起来。即登录到oracle上。所连接命令应该是应用程序的第一个可执行命令。连接命令格式如下:exec sql connect:& 用户名 & identified by : & 口令 &或exec sql connect: & 用户名 & / & 口令 &在使用上述两种格式进行登入时, 应当首先在说明段定义包含用户名和口令的 sql 变量,并在执行connect之前设置它们,否则会造成登录失败。例如:exec sql begin declare section ;varchar usename [20];varchar password[20];exec sql end declare ..........strcpy ( usename.arr, &csott&);usename.len = strlen (username.arr);strcpy (password.arr , &tiger&);password .len = strlen( password .arr);exec sql whenever exec sql connect :username indntified by :注意: 不能把用户名和口令直接编写到connect语句中,或者把用引号(&)括起来的字母串在connect 语句中, 如下面的语句是无效的。exec sql connect scott exec sql connect &scott& identified by &tiger&;(2). 插入、更新和删除在讲述sql语言时已详细讲过, 这里就不举例说明了。(3). 数据库查询及游标的使用在pro*c中, 查询可分为两种类型:l 返回单行或定行数的查询;l 返回多行的查询.此种查询要求使用游标来控制每一行或每一组(主变量用数组).1) 返回单行或定行数的查询在pro*c中的查询sql select语句由以下几个子句组成:selectintofromwhereconnect by unionintersectminusgroup by having order by 其中where子句中的查询条件可以是一个属性或多个属性的集合,在执行是赋值的主变量也可放在where子句中.where子句中所用的主变量称为输入主变量。如:select empno, job, sal into:pname, :pjob, :psalfrom empwhere empno=:若没有找到限定的行, 则sqlca.sqlcode返回&+1403&, 表明&没有找到&。into从句中的主变量叫输出主变量,它提供了查询时所需要的信息。在任何项送给主变量之前,都要求oracle把这些项转换成主变量的数据类型。对于数字是通过截断来完成的(如:9.23转换为9)。如果已确定查询只返回一行,那么就不必使用游标,只给select语句增加一个into子句即可。在语义上into语句在from之前的查询中有多少个选择项就有多少个输出主变量。若在select项中表达式的数目不等于into子句中主变量的数目,就把sqlca.sqlwarn[3]置为&w&。 2)多行查询及游标的使用如果查询返回多行或不知道返回多少行,使用带有oracle游标(cursor)的select语句。游标是oracle和pro*c存放查询结果的工作区域。一个游标(已命名的)与一条select语句相关联。操作游标有由4条命令:(1)declare cursor;(2)open cursor;(3)fetch;(4)close cursor。a. 定义游标一个游标必须首先定义, 才能使用它。语法为:exec sql declare 〈游标名〉corsor for select 〈列〉from 〈表〉例如:exec sql declare csor, cursor for 转载网上的一篇文章支持一下。proc是oracle数据库提供的编程接口之一,其应用十分的广泛,本文通过一个具体的例子,介绍proc编程的一些经验及应注意的地方。 例子程序: #include #include #include #include #include ex /*release_cursor=yes 使proc 在执行完后释放与嵌入sql有关资源*/ exec oracle option (release_cursor = yes); exec sql b varchar _user[20]; long al_empno=0; char ac_ename[11]=""; char ac_hiredate[20]=""; double af_sal=0; exec sql var ac_ename is string(11); exec sql var ac_hiredate is string(20); exec sql /*错误处理函数*/ void sql_error(char *msg) { printf("\n%s,%ld,%s\n", msg,sqlca.sqlcode,(char *)sqlca.sqlerrm.sqlerrmc); exec
exit(-1); } main() { exec sql whenever sqlerror do sql_error("oracle error: "); /*连接数据库*/ strcpy(_user.arr,"scott/tiger@demo"); vc_user.len=16; exec sql connect :vc_ exec sql declare cur_emp cursor for select empno, ename,to_char(hiredate,'yyyy/mm/dd hh24:mi:ss'), exec sql open cur_ while(1) { al_empno=0; strcpy(ac_ename,""); strcpy(ac_hiredate,""); af_sal=0; exec sql fetch cur_emp into :al_empno, :ac_ename:ename_ind, :ac_hiredate:hiredate_ind, :af_sal:sal_ if( sqlca.sqlcode == 1403) {
} printf("empno=%ld,ename=%s,hiredate=%s,sal=%lf\n",al_empno,ac_ename,ac_hiredate,af_sal); } exec sql close cur_ exec sql r } 1、宿主变量的声明 在proc中,在sql语句中用到的变量称为宿主变量。他们应在exec sql b与exec sql 之间声明,如上面所示.在声明宿主变量时应注意以下几点: (1) 在数据库表中定义为varchar2,varchar,char的字段,在proc中可声明为char,但长度应为它们在表中定义的长度加1,因为proc中 char型变量用做结尾。 如:ename在表中的定义为ename varchar2(10),在proc中可定义为: exec sql b char ename[11]; exec sql 常见错误说明: 如果插入的字符串长度大于10,如:exec sql insert into emp(ename) values('');会出现以下错误: error:ora-01480: str 赋值变量缺少空后缀。 如果定义为: exec sql b char ename[15]; exec sql 当插入的字符串长度大于10,小于15时,如:exec sql insert into emp(ename) values('');会出现以下错误: error:ora-01401: 插入的值对于列过大。 当插入的字符串长度大于15,如:exec sql insert into emp(ename) values('34');会出现以下错误: error:ora-01401:str 赋值变量缺少空后缀。 (2) 从sql语句中取字段的值到宿主变量中时,proc不会自动给宿主变量去掉右空格。而是以在declare section 中定义的长度为准(与 表中定义的无关)不足补右空格.如果不注意这一点,在proc中进行字符串操作时(如比较相等)会出错。如: exec sql b char ename[10]; exec sql 如果ename在表中的值为'abc',则取出的值为'abc '; 可用语句exec sql var重定义char型变量。这样宿主变量会自动去掉右空格。如下: exec sql b char ename[11]; exec sql var ac_ename is string(11); exec sql 如果ename在表中的值为'abc',则取出的值为'abc'; (3) 对浮点型的变量,为保证精度,最好是声明成double型的.因为double型的精度比float型高很多. (4) 整型可声明为long型(对较长的整型,而且所用的平台支持的话,如在sun平台上,可声明为long long型). (5) date型的处理:date型一般声明为char(20)。 往表中插入date型数据时,一般用to_date()函数进行类型转换,取出值时一般用to_char()函数进行类型转换. exec sql select to_char(hiredate,'yyyy/mm/dd hh24:mi:ss') into :ac_hire_date from emp where empno=1234; exec sql insert into emp(empno,hiredate) values(123,to_date(:ac_hiredate,'yyyy/mm/dd hh24:mi:ss'); 2、宿主变量的作用范围 如果宿主变量在所有的函数之外声明,则他们是全局变量。在使用之前要注意把变量的值初始化,宿主变量也可以在某个函数的内部定义。 这时他们是局部变量。一般都习惯把宿主变量声明为全局变量。 3、数据库的连接与断开 数据库的连接有以下两种方法: (1) strcpy(vc_user.arr,"scott/tiger"); vc_user.len=11; exec sql connect :vc_ (2) strcpy(user,"scott"); strcpy(pass,"tiger"); exec sql connect :user identified by : 注意:在有些平台上两种都可以,在有些平台上只能用第一种方法. 在proc程序中,要记住用exec sql r断开与数据库的连接,并释放相关的数据库资源。 4、proc中的null值的处理 如果某一字段取出的值是null,会报:sqlcode=-1405, sqlerr=ora-01405: 读取的列值为 null 并且相应的宿主变量的值不会被改变,为执行该sql语句之前的值. 常用的处理null值的方法有: (1)采用指示器变量,此时不会有-1405错误,当必须是所以为null的字段都有相应的指示器变量,如果某一字段没有指示器变量,但取出的值 为null值,则仍然会有-1405错误.当取出的值是null时,相应的指示器变量变量为-1,可根据指示器变量的值做响应的处理。 (2)如果字段较多,可取字段到一个结构体中及与该结构体对应的指示器结构体中.如上面的例子中可定义结构体: struct str_emp{ long al_ char ac_ char ac_ double af_ }; struct str_emp_ind{ long al_ char ac_ char ac_ double af_ }; struct str_emp str_ strcut str_emp_ind str_emp_ 在取之前可用memset(&str_emp,0,sizeof(str_emp)).清空该结构体,这样如果是字符型的null,会为"",整型的null会为0, 浮点型的会为0.00。此时不会有-1405错误。 (3)也可采用nvl()函数:举例如下: exec sql declare authors cursor for select empno, nvl(ename,chr(0)),nvl(to_char(hiredate,'yyyy/mm/dd hh24:mi:ss'),chr(0)),nvl(sal,0) 这样也不会有-1405错误不,当取出的值是null时,自动用nvl()中指定的值代替. chr(0)也可直接用''代替,如下: select empno, nvl(ename,''),nvl(to_char(hiredate,'yyyy/mm/dd hh24:mi:ss'),''),nvl(sal,0)5、proc中的错误的处理 所有的sql语句都有可能出错.所以都要加以判断,但每个sql语句后都加错误判断,太麻烦,可用一个函数如sql_error()来进行错误处理, 方法: (1)定义ql_error()函数。 (2)在开头加上exec sql whenever sqlerror do sql_error();这样当发生sqlca.sqlcode &0 的错误时,程序自动转到sql_error()中执行. 注意:对sqlca.sqlcode &0的错误如 sqlca.sqlcode =1403 是不会转到sql_error()中执行的. 另外:在unix下,可以用oerr 来查找错误的描述。如: ora ora -1405 查找错误号为-1405的描述. 6、proc中调用存储过程的方法 要把存储过程放在exec sql execute 和 end-之间,如下所示: 其中:al_empno,ac_ename 为输入参数,l_return,l_errno,c_errtext 为输出参数。 al_empno=8888; strcpy(ac_ename,"abcd"); exec sql execute begin up_db_emp(:al_empno,:ac_ename,:l_return,:l_errno,:c_errtext);
end- if (l_return != 0) { printf("调用up_pb_emp存储过程出错,errno=%ld,errtext=%s\n",l_errno,c_errtext); } 7、proc的命令行选项:proc编译器有很多的命令行选项,在命令行下直接不带参数运行proc,会列出所有的命令行选项来,并有说明。 (1)储存过程:编译储存过程是要带上用户名及密码 proc userid=scott/tiger sqlcheck=semantics ireclen=512 iname=test.cpp (2)parse=none 对非sql代码不进行语法分析,默认对非sql代码也进行语法分析. 在red had6.3上的oracle8.1.5中用proc时,会提示:/usr/include/stdio.h 及其他的.h文件中有错. 可把parse=none加上,就好了. 8、注意加上:exec oracle option (release_cursor = yes); release_cursor=yes 使proc 在执行完后释放与嵌入sql有关资源,保证在该proc程序执行完后,oracle不会锁住数据库资源,如锁表等。 如果在proc中用到oraca,还要在程序头加上: exec oracle option (oraca=yes); 9、proc中的类型转换 一、在c语言中: (1)字符型到整型可用atoi() atol(),sscanf() (2)整型,浮点型到字符型,可用sprintf() (3)字符型到浮点型用atof()不行,最好用sscanf(),举例如下: exec sql b double d_ float f_ char ac_text[20]="222"; exec sql (1)sscanf(ac_text, "%f", &d_demo); printf("ac_text=%s,d_demo=%f\n",ac_text,d_demo); (2)sscanf(ac_text, "%lf", &d_demo); printf("ac_text=%s,d_demo=%f\n",ac_text,d_demo); (3)sscanf(ac_text, "%f", &d_demo); printf("ac_text=%s,d_demo=%lf\n",ac_text,d_demo); (4)sscanf(ac_text, "%lf", &d_demo); printf("ac_text=%s,d_demo=%lf\n",ac_text,d_demo); printf("*******************\n"); (5)sscanf(ac_text, "%f", &f_demo); printf("ac_text=%s,f_demo=%f\n",ac_text,f_demo); (6)sscanf(ac_text, "%lf", &f_demo); printf("ac_text=%s,f_demo=%f\n",ac_text,f_demo); (7)sscanf(ac_text, "%f", &f_demo); printf("ac_text=%s,f_demo=%lf\n",ac_text,f_demo); (8)sscanf(ac_text, "%lf", &f_demo); printf("ac_text=%s,f_demo=%lf\n",ac_text,f_demo); 输出的结果: ac_text=222.00,d_demo=0.000000 ac_text=222.00,d_demo=222.000000 ac_text=222.00,d_demo=222.000032 ac_text=222.00,d_demo=222.000000 ******************* ac_text=222.00,f_demo=222.000000 ac_text=222.00,f_demo=0.000000 ac_text=222.00,f_demo=222.000000 ac_text=222.00,f_demo=0.000000 d_demo=atof(ac_text); printf("ac_text=%s,atof(ac_text)=%f\n",ac_text,d_demo); d_demo=atof(ac_text); printf("ac_text=%s,atof(ac_text)=%lf\n",ac_text,d_demo); f_demo=atof(ac_text); printf("ac_text=%s,atof(ac_text)=%f\n",ac_text,f_demo); f_demo=atof(ac_text); printf("ac_text=%s,atof(ac_text)=%lf\n",ac_text,f_demo); 输出的结果: ac_text=222.00,atof(ac_text)=000 ac_text=222.00,atof(ac_text)=000 ac_text=222.00,atof(ac_text)=000 ac_text=222.00,atof(ac_text)=000从上面的结果可见: double型应采用sscanf(ac_app_capcity, "%lf", &d_app); 打印用"%lf","%f" 都可以. (2),(4)正确 float型应采用sscanf(ac_app_capcity, "%f", &d_app); 打印用"%lf","%f" 都可以. (5),(7)正确 采用atof()转换的结果都是错的,所以不要用它。 二、写表或从表中取数据时: (1)字符型与整型之间可不用转换,采用默认方式。 (2)字符型与浮点型之间可不用转换,采用默认方式。 (3)日期型与字符型之间可用to_char(),to_date()。 10、proc中的4种动态sql简介 (1)动态sql1: 不能是查询(select)语句,并且没有宿主变量. 用法:拼一串动态sql语句,并用execute immediate执行,如: exec sql execute immediate "create table dyn1 (col1 varchar2(4))"; (2)动态sql2: 不能是查询(select)语句,并且输入的宿主变量数目是知道的, 用法:拼一串动态sql语句,用prepare,execute语句执行. strcpy(c_sql, "delete from emp where empno = :?"); exec sql prepare sql_stmt from :c_ exec sql execute sql_stmt using :emp_ (3)动态sql3: 用于创建动态查询, 并且要查询的字段及输入的宿主变量数目是知道的 用法: 拼一串动态sql语句,用prepare分析该语句,并要定义一个cursor进行取值 如:如要查询的数据按一年12月放到12张表中。表名为user_fee_1mon, user_fee_2mon,....可采用动态sql3来进行查询 strcpy(c_sql,"select c_user_id,c_user_name,to_char(t_date,'yyyy/mm/dd hh:mi:ss'),n_fee\n"); strcat(c_sql,"from user_fee_"); strcat(c_sql,ac_mon); strcat(c_sql," \n where c_user_id = :v1"); exec sql prepare s from :c_ exec sql declare cur_user_ exec sql open cur_user_fee using :ac_user_ while(1) { exec sql fetch cur_user_fee into :c_user_id,:c_user_name,:c_date,:n_fee); if (sqlca.sqlcode & 0) { /*fetch cursor失败*/ printf("fetch cursor cur_user_fee fail,sqlcode=%ld,sqlserr=%s",sqlca.sqlcode,sqlca.sqlerrm.sqlerrmc); } if( sqlca.sqlcode == sqlnotfound) {
} } exec sql close cur_user_ (4)动态sql4:要处理的字段及输入的宿主变量数目和主变量的类型事先是不知道的,如: insert into emp () values () 是最复杂的动态sql,很少用,在此不做介绍。 11、sqlca:sql是oracle的一个结构体,它的域用于最近的一条sql语句执行后的一些信息,如错误号,错误描述,警告,状态等。常用的 域介绍如下: sqlca.sqlcode:错误号,=0正确,=1403没取到数据 sqlca.sqlserrm.sqlerrmc:错误描述 sqlca.sqlerrd[3]:最近的一条sql语句所处理的行数,如果该语句处理失败,则它的值是不定的,如果错误在一个cursor操作中发生,则 它的值指已成功处理的行数.在delete,update中,它不包含因外键约束而删除,更新的那些行, delete from emp where dept='sale'; 在表emp中删除20行,但如果表emp与表address有外键约束,导致表address也被删除20行,则sqlca.sqlerrd[3]=20,而不是40。select ename , job, sal from empwhere deptno=:deptno;当赋给一个与查询相关联的游标cursor之后, 当select查询emp时可从数据库中返回多行,这些行就是cursor的一个活动区域。注意:1) 定义游标必须在对游标操作之前完成;2) pro*c不能引用没有定义的游标;3) 游标定义后,其作用范围是整个程序。所以对一个程序来讲, 同时定义两个相同的游标是错误的。 b. 打开游标打开游标的open语句主要用来输入主变量的内容,这些主要是where中使用的主变量。打开游标的语句是:exec sql open 〈游标名〉当打开游标后,可以从相关的查询中取出多于一行的结果。所有满足查询标准的行组成一集合,叫做"游标活动集"。通过取操作,活动集中的每一行或每一组是一个一个返回的,查询完成后, 游标就可关闭了。如图所示:定义游标:declare开始查询:select打开游标:open从活动集取数据:fetch查询完成关闭游标:close注意:1)游标处于活动集的第一行前面;2)若改变了输入主变量就必须重新打开游标。c. 取数据从活动集中取出一行或一组把结果送到输出主变量中的过程叫取数据。输出主变量的定义在取数据语句中。取数据的语句如下:exec sql fetch〈游标名〉into:主变量1,主变量2,&&fetch的工作过程如图所示:如图所示的查询结果指满足查询条件的查询结果。使用fetch应注意以下几点:l 游标必须先定义再打开。l 只有在游标打开之后才能取数据,即执行fetch语句。l fetch语句每执行一次,从当前行或当前组取数据一次,下一行或下一组向上移一次。游标每次所指的行或组都为当前行或当前组,而fetch每次都是取游标所指定的行或组的数据。l 当游标活动集空之后,orcle返回一个sqlca。sqlca(=1403)。l 若希望此游标再操作, 必须先关闭再打开它。l 在c程序中可以开辟一个内存空间,来存放操作结果,这样就能利用开辟的空间来灵活操纵查询的结果。 d.关闭游标取完活动集中所有行后,必须关闭游标,以释放与该游标有关的资源。关闭游标的格式为:exec sql close 游标名;例如:exec sql close c1;oracle v5.0版支持sql格式&current of cursor&。这条语句将指向一个游标中最新取出的行, 以用于修改和删除操作。该语句必须有取操作之后使用,它等同存储一个rowid,并使用它。(4).举例exec sql declare salespeople cursor for select ssno, name, salaryfrom employeewhere dname=&sales&;exec sql open salespeople;exec sql fetch salespeopleinto :ss,:name,:sal;exec sql close salespeople;(5)sql嵌套的方法及应用嵌入sql与交互式sql在形式上有如下差别:1) 在sql语句前增加前缀&exec sql&, 这一小小的差别其目的是在于预编译时容易识别出来, 以便把每一条sql作为一条高级语言来处理。2) 每一sql语句分为说明性语句和可执行语句两大类。可执行语句又分为数据定义、数据控制、数据操纵、数据检索四大类。可执行性sql语句写在高级语言的可执行处;说明性sql语句写在高级语言的说明性的地方。例如:在pro*c程序中建立一个名为book的表结构,过程如下:#include〈stdio.h〉exec sql begin declare section;varchar uid[20], pwd[20];exec sql end declare section;exec sql include sqlca;main(){ /*login database*/strcpy(uid.arr,&wu&);uid.len=strlen(uid,arr);strcpy(pwd.arr,&wu&);pwd.len=strlen(pwd.arr);exec sql connect:uid identifeed by:exec sql create table book ( acqnum number, copies number , price number);exec sqlpro*c可非常简便灵活地访问orcle数据库中的数据,同时又具有c语言高速的特点,因而可完成一些oracle产品不能完成的任务,例如以下一个固定的特殊格式输出结果。sql嵌套源程序示例#unclude&stdio.h&typedef char asciz[20];exec sql bexec sql type asciz is string (20)asciz emp_name(5);int emp_number(5a);float salary[5];exec sqlexvoid print_rows();void sqlerror();main(){int num_strcpy(username,&scott&);strcpy(password, &tyger&);exec sql whenever sqlerror do sqlerror();exec sql connect:username identified by:print (&\nconnected to oracle as user:%s\n&, username);exec sql declare c1 cursor forselect empno , ename ,exec sql open c1;num_ret = 0;for(;;){exec sql wheneveexec sql fetch c1 into : emp_number , :emp_name , :print_rows (sqlca.sqlerrd[2] & num_ret);num_ret=sqlca.sqlerrd[2];}if ((sqlca.sqlerrd[2] & num_ret)&0);print _rows(sqlca.sqlerrd[2] &num_ret);exec sql close c1;printf(&\have a good day.\n&);exec sql}void print_rows(n);{printf(&\nnumber employee salary\n&);printf(&------------------------------\n&);for (i=0;i&n; i++ )printf(&% - 9d%- 8s%9.2f\n&,emp-number[i], emp---name[i],salary[i];}void sqlerror(){exec sql whenevprintf(&\noracle error detected:\n&);printf(&\n%.70s\n&, sqlca.sqlerrm.sqlerrmc);exec sql rexit(1);}(6) 错误检测和恢复在使用sql语句和pro*c对数据库进行操作时,常常有字段空值,无条件删除,无行返回,数据溢出和截断等现象发生,这种现象可以用sqlca和指示器变量来检测。1 sqlca的结构在pro*c程序中sqlca结构如下:struct sqlca{char sqlcaid[8];struct{unsigned sqlerrm1;char sqlerrmc[10];}char sqlerrp[8];long sqlerrd[6];char sqlwarn[8];char sqlext[8];}其中:1) sqlca.sqlerrm.sqlerrmc:带有sqlca。sqlcode的错误正文。2) sqlca.sqlerrd:当前oracle的状态,只有sqlca.sqlerrd[2]有意义,表示dml语句处理的行数。3) sqlca.sqlwarn:提供可能遇到的条件信息。在每执行一个sql语句后,oracle就把返回结果放入sqlca中,但说明语句除外。用sqlca可以查看sql语句的执行结果。往往有三种结果:=0:执行成功;sqlca.sqlcode= &0:执行成功的状态值;&0:失败,不允许继续执行。2 指示器变量指示器变量有时也称指示变量.指示变量与一个主变量相关联,指出主变量的返回情况.=0:返回值不为空, 未被截断,值放在主变量中;返回值= &0:返回值为空, 忽略主变量的值;&0:主变量长度不够就被截断。使用指示变量要注意:l 在where子句中不能用指示变量。用null属性来测试空值。例如下列子句:select&from&where ename is null;是正确的,而where ename=:peme:peme1是错误的。l 指示变量在插入空值之前为&1l 可输出空值。3 whenever语句whenever是说明语句,不返回sqlcode, 只是根据sqlca中的返回码指定相关的措施。格式为exec sql whenever [sqlerror|sqlwarning|notforund][stop|continue|goto&标号&];其中(1)[stop|continue|got&标号&]的缺省值为continue。(2)sqlerror:sqlca.sqlcode&0;(3)sqlwarnign:sqlca.sqlwarn[0]=&w&;(4)notfound:sqlca.sqlcode=1403;下面给出一段程序来说明whenever的用法:exec sql begin deelare section;varchar uid[20];varchar pasw[20];&&exec sql end declare section;exec sql include sqlca;main(){&&exec sql whenever sqlerror goto err;exec sql connect:uid/:pwd;&&exec sql declare csor1 cursor forselect 〈字段〉form〈表〉exec sql open csor1;sql &&exec sql whenever not found goto good;for(;;)exec sql fetch csor, into&&good:&&printf(&\n查询结束\n&);exec sql close c1;exec sql whenever sqlerror continue.exec sql commit work release:exit();printf(&\n%70s|n&, sqlca.sqlerrm.sqlerrmc);exec sql rollback work release:exit(1);}(7) 动态定义语句sql语句分动态定义语句和静态定义语句两种:(1) 静态定义语句:sql语句事先编入pro*c中,在经过预编译器编译之后形成目标程序*。boj,然后执行目标程序预即可。(2) 动态定义语句:有些语句不能事先嵌入到pro*c程序中,要根据程序运行情况,用户自己从输入设备上(如终端上)实时输入即将执行的sql语句。动态定义语句有:l execute immediate;l prepare 与execute;l prepare与fetch 和 open ;l bind与define descriptor。1. execute immediate语句此语句表示立即执行, 并且只向sqlca返回执行结果,无其它信息。例如:exec sql begin declare section;varchar abcd[89];varchar deay[20];exec sql/** 输出字符串到abcd **/exec sql execute immediate :注意:1) execute immediate只能运行带一个参数的动态语句。其中,abcd是参数,不是关键字。2) execute immediate使用的先决条件是:sql语句不能包含主变量;sql语句不能是查询语句。3) 可用任何主变量作为execute immediate的参数;也可用字符串作为主变量。2. prepare与execute语句此语句表示&预编译/执行&。此语句能够预编译一次而执行多次。语法为:exec sql prepare 〈语句名〉from:主变量;exec sql execute〈语句名〉[using:替换主变量];prepare语句做两件事:(1) 预编译sql语句;(2) 给出sql语句的语句名。注意:l sql语句不能是查询语句;l prepare和execute可包含主变量;l prepare不能多次执行。例如:&example.pc&#define username &scott&#define password &tiger&#include &stdio.h&exexec sql bchar * username=char * password=varchar sqlstmt[80];int emp_varchar emp_name[15];varchar job[50];exec sqlmain(){exec sql whenever sqlerror goto :exec sql connect :username identified by :sqlstmt.len=sprintf(sqlstmt.arr,&insert into emp (empno,ename,job,sal)values(:v1,:v2,:v3,:v4)&);puts(sqlstmt.arr);exec sql prepare s from :for(;;){ printf(&\nenter employee number:&);scanf(&%d&,&emp_number); if (emp_number==0)printf(&\nenter employee name:&);scanf(&%s&,&emp_name.arr);emp_name.len=strlen(emp_name.arr);printf(&\nenter employee job:&);scanf(&%s&,job.arr); job.len=strlen(job.arr);printf(&\nenter employee salary:&);scanf(&%f&,&salary);}exec sql execute s using :emp_number,:emp_name,:job,:} 3. fetch语句和open语句fetch语句和open语句这组动态语句是对游标进行操作的,其执行过程如下:prepare〈语句名〉from 〈主变量字符串〉;declare〈游标名〉for〈语句名〉;open 〈游标名〉[using:替换变量1[,:替换变量变&]]fetch〈游标名〉into: 主变量1[,:主变量2&]close〈游标名〉注意:l sql语句允许使用查询语句;l select子句中的列名不能动态改变,只能预置;l where和order by 子句可以动态改变条件。一、 pro*c的编译和运行1. 先用oracle预编译器proc对pro*c程序进行预处理,该编译器将源程序中嵌入的sql语言翻译成c语言,产生一个c语言编译器能直接编译的文件。生成文件的扩展名为 .c2. 用c语言编译器cc 对扩展名为 .c的文件编译,产生目标码文件,其扩展名为 .o3. 使用make命令,连接目标码文件,生成可运行文件例如: 对上面的example.pc进行编译运行proc iname=example.pccc example.cmake exe=example objs=&example.o&example相关资料:|||||||oracle中pro*c的学习来源网络,如有侵权请告知,即处理!编程Tags:                &                    

我要回帖

更多关于 db2锁表 的文章

 

随机推荐