[Translate by z.jingwei. Document address: http://www-db.stanford.edu/~ setman/fcdb/oracle/or-proc.html]
Pro * c Introduction of embedded SQL
Summary Pro * C Syntax
SQL pre-processing instruction statement label host variable
Basic pointer structure array indicator variable data type equivalent dynamic SQL transaction error handling
SQLCA WHENEVER statement DEMO program C users list of embedded SQL Statements Supported by Pro * C
Summary SQL is a method of combining a high-level language such as C / C computing power and SQL database processing capabilities. It allows you to perform any SQL statement in the program. Oracle's embedded SQL environment is called Pro * C.
Pro * c program is compiled in two steps. First, the pre-compiler of Pro * C identifies the SQL statement embedded in the program and converts these statements to the appropriate calls for function (functions) in SQL Runtime Library. The output is pure C / C code and unprocessed pure C / C code. Then, compile the code with a conventional C / C compiler and generate an executable. For more detailed content, please refer to the Demo program.
Demo program.
Pro * C syntax
All SQL all SQL statements must start with Exec SQL and end with semicolons; The SQL statement can be placed anywhere in the C / C block, but the executable (SQL) statement should be behind the declaration statement. example:{
Int a;
/ * ... * /
Exec SQL SELECT SALY INTO: A
From Employee
WHERE SSN = 876543210;
/ * ... * /
Printf ("THE SALARY IS% D / N", A);
/ * ... * /
}
The preprocessing instructions can work normally in Pro * c, the C / C pre-processing instructions are #include and #if. Pro * c cannot recognize #define. The following code is wrong: #define the_ssn 876543210
/ * ... * /
Exec SQL SELECT SALY INTO: A
From Employee
Where ssn = the_ssn; / * invalid * /
The statement label can jump to the C / C mark EXEC SQL WHENEVER SQLERROR GOTO ERROR_IN_SQL in SQL;
/ * ... * /
Error_in_sql:
/ * Do Error Handling * /
We will talk about the meaning of WHENEVER in the following error handling section.
Error handling section
The meaning of WHENEVER.
Host variable
basis
The host variable is the key to connecting host programs and databases. The host variable expression must be considered (resolve to) left value (can be assigned). You can declare the host variable by declaring normal C variables. The statement of the host variable can be placed where any C variable declaration can be placed. (C users need to use "Declare Section"; refer to C Users) Oracle's C data types include:
C users) Oracle can use C data types include:
Char char [n] int short long float double varchar [n] - it is a pre-processing type (PSUEDO-TYPE) that can be identified by the pre-encoder of Pro * C. It is used to indicate the bell string of blank padding (Blank-padded, translation: '/ 0'). The PRO * C pre-encode converts it to a structural body having a 2-byte (Byte) long domain and an N-word (Byte). You can't specify register storage type (translation: pointer) as host variables.
You can use a colon in the SQL expression ":" to refer to a host variable, but you cannot use a semicolon in the C expression. When using a string as a host variable, the reference must be omitted; Pro * C understands that you are specifying a string based on the host variable declaration type (the description of this sentence is when defining a string as a host variable, char * Str = "string", when used in embedding SQL, omitted "*" instead of * STR). The expression cannot be used as a host variable without calculating C function calls and most pointers, even if they are indeed interpreted as left. The following code also illustrates the reference to the legitimate and illegal host variables:
INT DePtnos [3] = {000, 111, 222};
INT GET_DEPTNO () {return deptnos [2];
INT * GET_DEPTNOPTR () {Return & (Deptnos [2]);
int main ()
{
INT x; char * y; int Z;
/ * ... * /
Exec SQL INSERT INTO EMP (EMPNO, ENAME, DEPTNO)
VALUES (: x,: y,: z); / * legal * /
Exec SQL INSERT INTO EMP (EMPNO, ENAME, DEPTNO)
VALUES (: x 1, / * legal: the reference is to x * /
'Big Shot', / * Legal: But not really a host var * /
: deptnos [2]); / * Legal: Array Element is Fine * /
Exec SQL INSERT INTO EMP (EMPNO, ENAME, DEPTNO)
VALUES (: x,: y,
: (* (DEPTNOS 2)))))))))))); / * ILLEGAL: Although It Has ANLVALUE * /
Exec SQL INSERT INTO EMP (EMPNO, ENAME, DEPTNO)
VALUES (: x,: y,
: get_deptno ()); / * ILLEGAL: NO FUNCTION CALLS * /
Exec SQL INSERT INTO EMP (EMPNO, ENAME, DEPTNO)
VALUES (: x,: y,
: (* get_Depnoptr ())); / * ILLEGAL: Although It Has An Lvalue * /
/ * ... * /
}
The pointer can use the pointer declared in the SQL expression. I usually use a colon to do prefix: int * x;
/*...
EXEC SQL SELECT XYZ INTO: X from ...; this SELECT statement is written to * x, not x.
The structural structure can also be used as a host variable, as examples below: TypeDef struct {
Char name [21]; / * One Greater Than Column Length; for '/ 0' * /
Int SSN;
EMP;
/ * ... * /
Emp bigshot;
/ * ... * /
EXEC SQL INSERT INTO EMP (ENAME, ESSN)
VALUES (: bigshot);
Number of monologies use the host array below: int Emp_number [50];
Char Name [50] [11];
/ * ... * /
EXEC SQL INSERT INTO EMP (EMP_NUMBER, NAME)
VALUES (: EMP_NUMBER,: EMP_NAME); this will insert all 50 elements (tuples) at a time. Arrse can only be a one-dimensional array. CHAR NAME [50] [11] in the example may appear to contradict this rule, however, Pro * C actually treats Name as a one-dimensional string array rather than two-dimensional character arrays. Structural arrays can also be used. When the query result is stored using the query, if the size of the host array is smaller than the number of results returned after the actual query, only the N result is filled in the host array before (query).
The indicator variable indicator is actually an "NULL tag" after the host variable. Each host variable can be selectively associated into an indicator variable. The type of indicator variable must be 2 byte shaping values (short type), and must be followed by the host variable and is prefixed by colon. You can also use keyword indeicator between host variables and indicator variables. For example: Short Indicator_Var;
EXEC SQL SELECT XYZ INTO: HOST_VAR: INDICATOR_VAR
From ...
/ * ... * /
EXEC SQL INSERT INTO R
VALUES (: host_var indeicator: indeicator_var, ...); indicator variable used in the INTO clause of SELECT can be used to check the value of the return to the host variable is empty or truncated. Oracle can assign the value of the indicator variable with the following significance:
-1 field (translation: The original text is a column for this field) value is NULL, and the value of the host variable is uncertain. 0ORACLE assigns a complete value to the host variable. > 0ORACLE assigns the truncated field value to the host variable. The integral value returned by the indicator variable is the original length of the field. -2racle assigns the truncated field value to the host variable, but the original field value is uncertain. (Translation: This situation may be that the value of the value is cut after being cut, it cannot determine the original value)
You can also use the indicator variable to use the indicator variable in Insert or Update's VALUES and SET clauses to specify the host variable used to input to a null value. Your program can assign the value of the indicator variable has the following significance:
-1racle will ignore the value of the host variable and assign a NULL value to the field. > = 0ORACLE assigns the value of the host variable to the field.
Data Types Equation Oracle Cognition Two Data Types: Internal Types and External Types. The internal data type indicates how the Oracle stores fields in the database table. The external data type indicates how to format the value stored in the host variable for input or output. In the pre-edlation period, each host variable will be given a default Oracle external data type. Data types equivalent allow you to overload the default equivalence and allow you to control the formatting of Oracle input data and output data. Equivation is achieved based on the conversion from variables to variables by using a VAR expression. The syntax is: exec SQL VAR
EXEC SQL VAR EMP_NAME IS STRING (21); the length of the ENAME field in the EMP table is 20 characters (here, there is a need to assign 21 characters to accommodate the '/ 0' end. Oracle's external data type String is an interface that specially designed for C type strings. Oracle automatically ends with '/ n' when passing the ename field value to EMP_NAME. You can also use the TYPE statement to classify the user-defined data type as an Oracle external data type. The syntax is: EXEC SQL TYPE
MY_RAW BUFFER;
/ * ... * /
Buffer = malloc (4004) Here, we allocate more memory than the source type long (4000), because the pre-compiler returns the length and may need to populate the appropriate length to meet the system's alignment requirements.
Dynamic SQL embedded SQL can meet a fixed application, but sometimes dynamically generate a complete SQL statement is also important. For dynamic SQL, statement stores in string variables, Prepare converts strings to SQL statements and executes this statement with Execute. Consider the following example: char * s = "INSERT INTO EMP VALUES (1234, 'Jon', 3)";
Exec SQL prepare Q from: s;
Exec SQL EXECUTE q; Prepare and Execute can be placed in a statement, like this: char * s = "INSERT INTO EMP VALUES (1234, 'Jon', 3)"
EXEC SQL EXECUTE IMMEDIATE: S;
Transaction Oracle Pro * c supports standard SQL definition transactions. A business is a set of SQL statements, Oracle is running it as a separate unit. When a transaction starts from the first SQL statement, "EXEC SQL Commit" (executing the current transaction is permanently modified) or "EXEC SQL ROLLBACK" (canceling any modification from the transaction to the current location to end the transaction) . After the current transaction is ended by the COMMIT or ROLLBACK statement, the next executable SQL statement will automatically start a new transaction. If you do not execute an Exec SQL Commit at the end of the program, the modifications to the database will be ignored.
Error Processing After each executable SQL expression, you can check SQLCA explicitly or use the WHENEVER statement in the program to implicate execution status information. Below will be described in detail below.
Sqlcasqlca (SQL Communications Area, SQL Communication Area) is used to check errors and status changes in the program. After each executable SQL statement is executed, the Oracle runs in this structure in this structure. If you want to use SQLCA, you have to use #include to include the SQLCA.h header file. If you have a header file in many places, you have to use #undef SQLCA to cancel the macro definition of SQLCA. The related blocks in SQLCA.H are as follows: #ifndef Sqlca # define SQLCA 1
Struct sqlca {
/ * UB1 * / CHAR SQLCAID [8];
/ * b4 * / long sqlabc;
/ * b4 * / long sqlcode;
Struct {
/ * ub2 * / unsigned short sqlerrml;
/ * UB1 * / CHAR SQLERRMC [70];
SQlerrm;
/ * UB1 * / CHAR SQLERRP [8];
/ * b4 * / long sqlerrd [6];
/ * UB1 * / CHAR SQLWARN [8];
/ * ub1 * / char sqlext [8];
}
/ * ... * / SQLCA domain has the following significance:
SQLCAID This string is initialized to "SQLCA" to indicate that this is a SQL communication area. SQLCABC This integer domain identifies the length of the SQLCA structure with a Byte. SQLCode This integer domain identifies the status code of the recently executed SQL statement:
0 There is no error. > 0 statement execution but capture exceptions. This happens when Oracle finds no records according to WHERE conditions, or Select INTO or FETCH affects the number of records 0. <0 Since an error Oracle cannot perform a SQL statement. When this error occurs, the current transaction should roll back (ROLLBACK).
SQlerRM This inner structure contains two domains:
SQlerrml - The length of information saved in SQlerRMC. SQlerRMC - Information text up to 70 characters (Character), similar to the error code stored in SQLCode. SQLERRP retains SQlerRD This binary plastic array contains 6 elements:
SQlerrd [0] - Keep SQlerRD [1] - Reserved SQlerRD [2] - the number of records that are affected by the recently executed SQL statement. SQlerrd [3] - Keep SQlerRD [4] - Analysis of the error of the recent execution statement error, error start character offset. SQlerrd [5] - Reserved SQLWARN The single-character array contains 8 elements for warning signs. Oracle Sets a tag using character 'w'.
SQLWARN [0] is set when other tags are set. SQLWARN [1] Sets when the output host variable is saved is the truncated field value. SQLWARN [2] When calculating SQL statistics such as AVG or SUM, if a NULL field cannot be used when used. SQLWARN [3] When the number of SELECT's field is equal to the number of host variables specified in the INTO sentence. SQLWARN [4] Did you have a UPDATE or DELETE statement that uses the WHERE clause to process each line of data tables. SQLWARN [5] is set when the ProCedure / Function / Package / Package Body creates commands due to PL / SQL compilation errors. Sqlwarn [6] no longer uses SQLWARN [7] no longer use
SQLEXT reserved
SQLCA can only store error messages for up to 70 characters in the SQlerRM domain. To get a longer (or nested) all error message characters, you can use SQLGLM () functions: void sqlglm (char * msg_buf, size_t * buf_size, size_t * msg_buf is the character buffer of Oracle storage error information; buf_size Specifies the length of MSG_buf; Oracle stores the actual error message in * msg_length. The maximum length of Oracle error message is 512 bytes (Byte). WHENEVER statement This expression is automatically incorrect checking and processing. The syntax is: exec SQL WHENEVER
Sqlwarning - Sqlwarn [0] SQLERROR - SQLCODE is not found because Oracle returns an error, SQLCODE value is negative not found - because Oracle Press WHERE Conditions Nothing to find any record, or select INTO or FETCH Returns 0 records And make SQLCode as positive
Continue - As long as it may, the program will try to continue running the statement DO - program hand over the control module Goto
EXEC SQL WHENEVER NOT FOUND GOTO HANDLE_EMPTY; below is a more detailed example: / * code to find student name given id * /
/ * ... * /
For (;;)
{
Printf ("Give Student ID Number:");
Scanf ("% d", & id);
Exec SQL WHENEVER NOT FOUND GOTO NOTFOUND;
Exec SQL Select StudentName Into: ST_NAME
From student
Where studentid =: ID;
Printf ("Name of Student IS% s. / n", ST_NAME);
CONTINUE;
NOTFound:
Printf ("No Record EXISTS for ID);
}
/ * ... * / Note that the WHENEVER expression does not follow the scope rules of standard C, the entire program is its scope. For example, if the following statements are in your program (such as before a loop): Exec SQL WHENEVER NOT FOUND DO BREAK; all SQL statements that appear after this file will be affected. When you don't need WHENEVER to affect the program (such as after your loop), make sure you use the following statement to cancel it. EXEC SQL WHENEVER NOT Found Continue;
Demo program Note: The routine will be created, using four tables: DEPT, EMP, PAY1, and PAY2. Note that there may be the same name in your database! There are many routines under the LELAND system / AFS / IR / CLASS / CS145 / CODE / PROC. They are named sample * .pc (c users) and cppdemo * .pc (C users). ".pc" is an extension of Pro * C code. Due to a few fixed steps, these files are copied, so don't copy them. The following describes how to download and set up routines: Confirm that you have already run Source /AFS/IR/Class/cs145/all.env in your directory, run load_samples
PROC INAME = Sample1.pc converts embedded SQL code to the corresponding library call, outputs Sample1.c cc
(Deptno Number (2) Not NULL,
DNAME VARCHAR2 (14),
Loc varchar2 (13));
CREATE TABLE EMP
(Empno Number (4) Not Null,
ENAME VARCHAR2 (10),
Job varchar2 (9),
Mgr Number (4),
HIREDATE DATE,
Sal Number (7, 2),
COMM Number (7, 2),
DEPTNO NUMBER (2));
Create Table PAY1
(ENAME VARCHAR2 (10),
Sal Number (7, 2));
CREATE TABLE PAY2
(ENAME VARCHAR2 (10),
Sal Number (7, 2)); These tables are automatically created when running load_samples in step 2. Some tuples (translation: no right words, put the original word this) is also inserted. You can view these tables before the program run (such as insert, delete or update tuples). These tables are automatically deleted when you run Clean_SAMPle. Note: Clean_sample will also clean the entire
How to connect to Oracle How to use SQL in C / C How to use the host variable with database communication How to use the host variable and database communication How to use WHENEVER How to use the indicator variable detection output Null value now, you can use these Technologies write your own database application. And has fun!
C users want to generate the appropriate C code using the precompiler, you need to pay attention to the following:
The code is expanded by the precompiler. To get C code, you need to set the code = CPP option when you execute the Proc.
Resolve the ability. The PARSE option of Proc can be the value below:
PARSE = None. C pre-processing instructions can only be parsed in the declaration festival, so all host variables need to be declared in the declaration festival.
PARSE = Partial. C pre-processing instructions can be parsed; however, all host variables need to be declared in the declaration festival.
PARSE = FULL. C pre-processing instructions can be parsed, and the host variables can be declared anywhere. This is the default setting when Code is not CPP; but when Code = CPP, specifies PARSE = FULL is an error.
Therefore, C users must specify
PARSE = None or
PARSE = Partial, so this also lost freedom in any place to declare the host variable. More, the host variable must be packaged in a declaration festival, as follows:
EXEC SQL Begin Declare Section;
// Declarations ...
Exec SQL End Declare Section; You need to use this method to declare all hosts and indicator variables.
File extension. You have to specify settings CPP_SUFFIX = CC or CPP_SUFFIX = C.
The header file is positioned. By default, the ProC looks up the header file like a standard positioning stdio.h file. However, C has its own header file, such as iostream.h, is placed elsewhere. So, you need to specify the path to the PROC lookup header file using the SYS_INCLUDE option.
Pro * c Supported embedded SQL statement list
Disclaimer Expression EXEC SQL Arraylen In PL / SQL Using Host Variables Exec SQL Begin Declare Section Exec SQL End Dec SQL Declare Give Oracle Naming EXEC SQL INCLUDE Copy EXEC SQL TYPE Equation Data Type EXEC SEC SQL VAR same variables EXEC SQL WHENEVER error executing the expression EXEC SQL ALLOCATE statement processing operation, the control Oracle data EXEC SQL ALTEREXEC SQL ANALYZEEXEC SQL AUDITEXEC SQL COMMENTEXEC SQL CONNECTEXEC SQL CREATEEXEC SQL DROPEXEC SQL GRANTEXEC SQL NOAUDITEXEC SQL RENAMEEXEC SQL REVOKEEXEC SQL TRUNCATEEXEC SQL CLOSEEXEC SQL DELETE sorting, modification Oracle data EXEC SQL EXPLAIN PLANEXEC SQL FETCHEXEC SQL INSERTEXEC SQL LOCK TABLEEXEC SQL OPENEXEC SQL SELECTEXEC SQL UPDATEEXEC SQL COMMIT processing services EXEC SQL ROLLBACKEXEC SQL SAVEPOINTEXEC SQL SET TRANSACTIONEXEC SQL DESCRIBE using dynamic SQLEXEC SQL EXECUTEEXEC SQL PREPAREEXEC SQL ALTER sESSION control session EXEC SQL SET ROLEEXEC SQL EXECUTE END-EXEC embedded PL / SQL block This document was written originally by Ankur Jain and Jeff Ullman for CS145, Autumn 1997; revised by Jun Yang for Prof. Jennifer Widom's CS145 class in Spring, 1998; further revisions By Roy Goldman for Prof . Jeff Ullman's CS145 Class in Autumn, 1999; Further Revisions by Calvin Yang for Prof. Jennifer WiDom's CS145 Class In Spring, 2002.