Académique Documents
Professionnel Documents
Culture Documents
INTRODUCTION
Here we shall discuss some of the methods that have been developed for accessing databases from programs. They are developed using general-purpose programming language like Java, C/C++/C#, COBOL, etc., or scripting languages like PHP and JavaScript, etc for web applications The general-purpose programming language is called the host language, whereas the database language SQL, in our caseis called the data sublanguage. Special database programming languages are developed specifically for writing database applications like PL/SQL (Oracle), MySQL stored procedures (a procedural language that closely adheres to SQL/PSM), PL/pgSQL (PostgreSQL language similar to SQL/PSM and PL/SQL), Transact-SQL (Microsoft and Sybase equivalent) etc. The purpose of the chapter is to introduce some of the main types of database programming techniques and to compare them
to illustrate the main differences that a programmer would face when using each of these database programming techniques Example concepts include embedded SQL, dynamic SQL, SQL/CLI, ODBC, JDBC etc
PL/SQL Example
SQL> select * from student; REGNO SNAME ---------- -------------------1 Isaac 2 Fatima 3 Ibeltha 4 Zenab 5 Henry 6 Mohamed 7 Getachew 8 Seid 9 David 10 Solomon 10 rows selected.
SQL> get pre_except 1 declare 2 s student.sname%type; 3 begin 4 select sname into s from student 5 where regno = 11; 6 Exception 7 when no_data_found then 8 dbms_output.put_line('Student 9 detail Not Found'); 10* end; SQL> / Student detail Not Found
Impedance Mismatch
It refers to the problems that occur because of differences between the database model and the programming language model. For example, the practical relational model has three main constructs: columns (attributes) and their data types, rows (also referred to as tuples or records), and tables (sets or multisets of records). Problems
The data types of the programming language differ from the attribute data types that are available in the data model. Hence, a different binding for each host programming language for each attribute type is needed. (for C++, Java etc) the results of most queries are sets or multisets of tuples (rows), and each tuple is formed of a sequence of attribute values. A binding is needed to map the query result data structure (table) . Hence a cursor or iterator variable is typically used to loop over the tuples in a query result.
Interact with the database by submitting queries, updates, and other database commands. Terminate or close the connection to the database.
There can be multiple connections but in certain cases only one connection can be active at a time
AUTHORIZATION <user account name and password> ; -- to establish connection SET CONNECTION <connection name> ; -- to set an active connection DISCONNECT <connection name> ; -- to disconnect a connection EXEC SQL include SQLCA ; -- Communication variables SQLCODE and SQLSTATE found in SQLCA
communication variables are used by the DBMS to communicate exception or error conditions to the program
Cursors
Applicable for both Embedded SQL and DB Server-side programming Cursor is a pointer / iterator that points to a single tuple (row) from the result of a query that retrieves multiple tuples. The cursor is declared when the SQL query command is declared in the program. An OPEN CURSOR command fetches the query result from the database and sets the cursor to a position before the first row in the result of the query. This becomes the current row for the cursor. FETCH commands are issued to move the cursor to the next row in the result of the query CLOSE CURSOR command is issued to indicate the processing with cursor is done.
8) EXEC SQL OPEN EMP ; 9) EXEC SQL FETCH from EMP into :ssn, :fname, :minit, :lname, :salary ; 10) while (SQLCODE == 0) { 11) 12) 13) 14) 17) 18) } printf("Employee name is:", Fname, Minit, Lname) ; prompt("Enter the raise amount: ", raise) ; EXEC SQL update EMPLOYEE set Salary = Salary + :raise where CURRENT OF EMP ; EXEC SQL FETCH from EMP into :ssn, :fname, :minit, :lname, :salary ;
open calc_result;
for i in 1..c loop
close calc_result;
The connection established is set as the default context for subsequent commands. In SQLJ, the embedded SQL commands within a Java program are preceded by #sql instead of the keywords EXEC SQL
For queries that retrieve many tuples, SQLJ uses the concept of an iterator, which is similar to a cursor in embedded SQL.
Write a program import java.sql.DriverManager; import java.sql.Connection; import java.sql.SQLException; public class OracleJDBC { public static void main(String[] argv) { System.out.println("----- Oracle JDBC Connection Testing ----"); try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { System.out.println("Where is your Oracle JDBC Driver?"); e.printStackTrace(); return; } System.out.println("Oracle JDBC Driver Registered!"); Connection connection = null; try { connection = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:melita", "username", "password"); } catch (SQLException e) { System.out.println("Connection Failed! Check output console"); e.printStackTrace(); return; } if (connection != null) { System.out.println("You made it, take control your database now!"); } else { System.out.println("Failed to make connection!"); } } }
Execute C:\jdbc-test>javac OracleJDBC.java C:\jdbc-test>java -cp c:\jdbctest\ojdbc6.jar;c:\jdbc-test OracleJDBC ------ Oracle JDBC Connection Testing ------Oracle JDBC Driver Registered! You made it, take control your database now!
Although dynamic SQL is preferable, it is much more complicated as the types or number of attributes to be retrieved is unknown at the time of writing code.
2) EXEC SQL END DECLARE SECTION ; ... 3) prompt("Enter the Update Command: ", sqlupdatestring) ;
4) EXEC SQL PREPARE sqlcommand FROM :sqlupdatestring ; 5) EXEC SQL EXECUTE sqlcommand ; ...
A Procedure is a subprogram that performs a specification. A procedure has two parts namely, specification and body. Procedure specification is from the procedure keyword to the parameter list and the procedure body is from the IS keyword to the End keyword.
Output:
SQL> select * from student_marks; REGNO MARK1 MARK2 TOTAL ---------- ---------- ---------- ---------1 67 90 157 2 78 56 3 23 56 SQL> select * from student_result; REGNO STATUS ---------- ---1 pass 2 3
SQL> get proc_result; 1 create or replace procedure pro_result (reg number, m1 number, 2 m2 number) 3 is 4 mark number(3); 5 begin 6 update student_marks set total = mark1 + mark2 where 7 regno = reg; 8 mark := (m1+m2)/2; 9 if mark >= 50 then 10 update student_result set status = 'pass' where regno = reg; 11 else 12 update student_result set status = 'fail' where regno = reg; 13 end if; 14* end; SQL> / Procedure created. SQL> exec pro_result(1,67,90); PL/SQL procedure successfully completed.
SQL> get calc_grade 1 create or replace function grade_fn (mark number) 2 return char 3 is 4 gd char; 5 begin 6 if mark >= 90 then 7 gd:= '0'; 8 elsif mark >= 80 and mark < 90 then 9 gd:='A'; 10 elsif mark >= 70 and mark < 80 then 11 gd:='B'; 12 elsif mark >= 60 and mark < 70 then 13 gd:='C'; 14 elsif mark >= 50 and mark < 60 then 15 gd:='D'; 16 else 17 gd:='F'; 18 end if; 19 return gd; 20* end; 21 / Function created.