Embedding SQL

Preview:

DESCRIPTION

 

Citation preview

1

 

SQL in higher level languages

2

 SQL in higher level languages

Why do we want to use SQL in a higher level language?

1) Read in data from file, insert into relation

Loop until the EOF read values from file – higher level

code manipulate values with higher level

code insert into relation values (SQL)

End loop

3

Why cont’d

2) Compute results based on result from query e.g. generate a report

Query databaseCompute results from queryPrint results

3) Provide a user interface for SQL if the current

one is lackingPrompt user for querySend query to DBMSReceive resultsDisplay results to user

4

Must have:

to do 1) must read in values into C variables then use those values to insert using SQL

still need SQL statement to insert, select tuples

to do 2) must be able to manipulate results from SQL query, but mismatch between C and SQL

sets versus one record at a time

to do 3) need to accept queries from user - create SQL queries

5

Given the query: Select dnumber

From department Where mgrssn = 987654321

What is needed?– Variables in which to place result (Host variables)– Processing of result table (cursors)– Data structure for communicating with DBS in case of

errors (SQLCA)– What if we want to process any query typed in?

(Dynamic SQL)

6

To do this

Can use: 1. embedded SQL

Precede each statement with EXEC SQL

2. Platform specific classes, interfaces

Oracle’s OLE

3. Platform independent classes, interfaces

JDBC

7

Host variables :

• Referenced by SQL and higher level language

– Declared as C++ variables, used in SQL statements

• Prefixed with : in SQL statements

• transmit data between DB manager and application

• Used in all methods

ORACLE host variables

• Oracle and C/C++ types Data types: (ANSI SQL vs. Oracle)

• some conversions are possible

• Previously, in embedded SQL no arrays allowed except char

• Oracle 9i allows host variables to be arrays

8

9

Cursors 

• How to access multiple rows from a query result?

•   Use a cursor – A cursor points to 1 row– As the cursor is incremented, the values of

rows are retrieved into host vars– Can scroll forward, backwards, etc.

10

SQLCA

• SQL communication area - a structure• used for communication between DBS

monitor and C++ program• allocates program space for errors and

starts communication by DBS monitor• after each SQL statement executed, a new

value is placed in SQLCA• indicates if successful, EOF, etc.• error or warning conditions

11

Error messages

• printing error messages - can extract the error message

• Available through SQLCA

 

1. Embedded SQL

• Must place EXEC SQL before each SQL statement

• Place result into host variables or cursor– This example returns 1 row (host variables)

EXEC SQL select lname, salary

into :lname, :sal

From employee

Where ssn=123456789;

• Inserts row into tableEXEC SQL insert into project values

(:projectName, :projectNum, :projectLocation, :departmentNumber)

12

Embedded SQL

EXEC SQL SELECT ENAME, EMPNO, SAL

INTO :emp_name, :emp_number, :salary FROM EMP WHERE SAL > 1000;

Returns > 1 row do need:

char emp_name[50][20];

int emp_number[50];

float salary[50];

13

Embedded SQL - Arrays

• If there are < 50 rows, will work.

• If there are > 50 rows, it will not work. Retrieves the first 50 rows again.– Therefore, if you do not know the maximum

number of rows a SELECT will return, you can declare and open a cursor, then fetch from it in "batches."

14

15

Using cursors

• 3 steps involved:–   1) declare cursor - just a definition of the

select– 2) open cursor - executes select, builds

result table• Declare/open can be as one

– 3) fetch results - to navigate through the results

Cursors

EXEC SQL declare c1 cursor for Select essn, hours From WORKS_ON Where pno = :proj_id;

EXEC SQL open c1;

EXEC SQL fetch c1 into :essn_id, :hrs; while (sqlca.sqlcode == 0) // checks for EOT

{ cout << essn_id << “ “ << hrs << endl;

EXEC SQL fetch c1 into :essn_id, :hrs;          

  }; 16

17

SQLCA

• sqlca.sqlcode - testing code part of structure– sqlcode = 0 successful sql call– < 0 error– > 0 warning - call successful but some

condition existed

e.g. EOF is 100 (DB2, Ingres, but not ORACLE)

• sqlerrd[2] - indicates number of row affected by insert, update or delete (used for referential integrity)

Whenever

• Can test sqlcode directly or use whenever

EXEC SQL whenever condition action;

• condition can be:– sqlerror - tests of sqlcode < 0– not found - tests when no rows affected -

good for EORows in ORACLE– sqlwarning - tests if sqlcode > 0, other than

not found

18

Error messages – Embedded SQL

• printing error messages in ORACLE - can extract the error message

• The following can be defined by the user:

int report_error () { cout << "error occurred" << endl;

sqlca.sqlerrm.sqlerrmc[sqlca.sqlerrm.sqlerrml]= '\0'; cout << sqlca.sqlerrm.sqlerrmc << endl; return -1;

}

EXEC SQL whenever sqlerror do report_error();

19

20

Dynamic SQL

• Dyanmic SQL– Useful when:– Format of SQL statement is not known - can

generate during execution– Statement known but objects referenced

don't exist at compile time

21

Dynamic SQL

• Dynamic SQL– Place SQL query into character string

char st[80] = " "; // in Declare Section strcpy (st, "Delete From employee where"); cin >> field; strappend (st, field); strappend (st, "> :val");

//Resulting query is:// “Delete From employee where salary > :val” EXEC SQL Execute immediate st;

22

How does Embedded SQL work

• Since it is a C/C++ program, must be able to compile

• Hence, must precompile to identify SQL statements

• SQL statements are replaced with calls to SQLLIB routines (API calls to data manager that are recognized by C/C++)

23

Precompiler for Oracle

• start with a source file: fn.pc• Precompiler generates file: fn.c/fn.cpp

– (internal representation of SQL statements that were replaced by calls to SQLLIB routines- orasql9.lib)

– if examine fn.c/fn.cpp can see all the SQLLib calls

• Then you compile your program using C/C++

24

What is needed in .NET to use Oracle? • Must set up the environment

– Add path for oracle executable files• C:\Program Files\Oracle\Ora90\bin

– Add path for Oracle include files• C:\Program Files\Oracle\Ora90\precomp\public

– Add path for Oracle library files• C:\Program Files\Oracle\Ora90\precomp\lib\msvc

– Add orasql9.lib for Linker

25

Connect

• must connect to DBMS

• Include the following in C/C++ program EXEC SQL connect :user_name identified by :user_pwd

using :host_string;

EXEC SQL disconnect;

Sample program

26

OLE, JDBC

• OLE methods are available in Oracle to do most of the above

• Can also use JDBC, independent of platform

Recommended