SQL in higher level languages

Post on 15-Nov-2014

676 views 0 download

Tags:

description

 

Transcript of SQL in higher level languages

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

Embedded SQL

• Must place EXEC SQL before each sql statement

• Place result into host variables or cursor

EXEC SQL select lname, salary

into :lname, :sal

From employee

Where ssn=123456789;

7

8

Host variables :• Referenced by SQL and higher level language• Prefixed with : in SQL statements• transmit data between DB manager and application

• Used in all methods – Embedded SQL example

EXEC SQL select ssn from employee where salary < :min

insert into project values (:projectName, :projectNumber, :projectLocation, :departmentNumber)

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

9

Embedded SQL

char emp_name[50][20];

int emp_number[50];

float salary[50];

EXEC SQL SELECT ENAME, EMPNO, SAL

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

10

Embedded SQL - Arrays

• If there are < 50 rows, will work.

• If there are > 50 rows, it will not work. If you reissue the select statement, it will retrieve 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."

11

12

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.

13

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

14

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

15

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)

Example

EXEC SQL fetch c1 in :hv1;

while (sqlca.sqlcode == 0) {

cout << hv1 << endl;

EXEC SQL fetch c1 into :hv1;

}

16

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

17

18

Error messages

• printing error messages - can extract the error message

• Available through SQLCA

 

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

Updating

• Delete– Delete tuples from base table– Positioned delete, use cursor

• Updates– Makes changes to base table– Positioned delete, use cursor

• Insert– No need for cursor, can't specify position of new row

• DDL– Can create tables, etc.

21

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

22

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;

23

Parameter markers ?

Can pass query as character string (dynamic SQL) “update employee

set salary = salary*1.1 where dno = ? and sex = ?”

• We need to identify the variable that we will obtain later

• Depending on system, use ? or : as a parameter marker– Oracle uses “:”

• An SQL statement can contain more than one parameter marker

24

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++)

25

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++

26

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

27

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

28

OLE, JDBC

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

• Can also use JDBC, independent of platform