Database Application Programs PL/SQL, Java and the Web

Similar documents
Types of Databases. Types of Databases. Types of Databases. Databases and Web. Databases and Web. Relational databases may also have indexes

Database Programming Overview. COSC 304 Introduction to Database Systems. Database Programming. JDBC Interfaces. JDBC Overview

CSC System Development with Java. Database Connection. Department of Statistics and Computer Science. Budditha Hettige

JAVA AND DATABASES. Summer 2018

INTRODUCTION TO JDBC - Revised spring

INTRODUCTION TO JDBC - Revised Spring

COSC344 Database Theory and Applications. Lecture 11 Triggers

Wentworth Institute of Technology COMP570 Database Applications Fall 2014 Derbinsky. SQL Programming. Lecture 8. SQL Programming

Discuss setting up JDBC connectivity. Demonstrate a JDBC program Discuss and demonstrate methods associated with JDBC connectivity

ICOM 5016 Database Systems. Database Users. User Interfaces and Tools. Chapter 8: Application Design and Development.

ERwin and JDBC. Mar. 6, 2007 Myoung Ho Kim

DB I. 1 Dr. Ahmed ElShafee, Java course

13 Creation and Manipulation of Tables and Databases

Instructor: Jinze Liu. Fall 2008

The Web Application Developer s. Red Hat Database. View. October 30, Webcast. Patrick Macdonald, Fernando Nasser. Red Hat Database Engineering

Announcements. SQL: Part IV. Transactions. Summary of SQL features covered so far. Fine prints. SQL transactions. Reading assignments for this week

Programming the Database

SQL: Programming Midterm in class next Thursday (October 5)

Working with Databases and Java

You write standard JDBC API application and plug in the appropriate JDBC driver for the database the you want to use. Java applet, app or servlets

Database Technology. Topic 6: Triggers and Stored Procedures

Outline. Lecture 10: Database Connectivity -JDBC. Java Persistence. Persistence via Database

Database Application Development

JDBC [Java DataBase Connectivity]

a. Jdbc:ids://localhost:12/conn?dsn=dbsysdsn 21. What is the Type IV Driver URL? a. 22.

Database Applications. SQL/PSM Embedded SQL JDBC

Running SQL in Java and PHP

SQL: Programming. Announcements (September 25) Motivation. CPS 116 Introduction to Database Systems. Pros and cons of SQL.

Assertions, Views, and Programming. CS157A Chris Pollett Oct. 31, 2005.

Inf 202 Introduction to Data and Databases (Spring 2010)

JDBC, Transactions. Niklas Fors JDBC 1 / 38

The Design of JDBC The Structured Query Language Basic JDBC Programming Concepts Query Execution Scrollable and Updatable Result Sets

Servlet 5.1 JDBC 5.2 JDBC

Databases 2012 Embedded SQL

COMP102: Introduction to Databases, 23

Running SQL in Java and PHP

COP4540 TUTORIAL PROFESSOR: DR SHU-CHING CHEN TA: H S IN-YU HA

Introduction to SQL Server. nikos bikakis

Why use a database? You can query the data (run searches) You can integrate with other business systems that use the same database You can store huge

Overview. Database Application Development. SQL in Application Code. SQL in Application Code (cont.)

Database Application Development

Database Application Development

SQL in a Server Environment

Accessing databases in Java using JDBC

Part I: Stored Procedures. Introduction to SQL Programming Techniques. CSC 375, Fall 2017

DataBase Lab JAVA-DATABASE CONNECTION. Eng. Haneen El-masry

Enterprise Java Unit 1- Chapter 6 Prof. Sujata Rizal

Questions and Answers. A. A DataSource is the basic service for managing a set of JDBC drivers.

Cyrus Shahabi Computer Science Department University of Southern California C. Shahabi

Application Programming for Relational Databases

DATABASE DESIGN I - 1DL300

Java Database Connectivity (JDBC) 25.1 What is JDBC?

Lab # 9. Java to Database Connection

IELM 511 Information Systems Design Labs 5 and 6. DB creation and Population

Programming in Java

JDBC Architecture. JDBC API: This provides the application-to- JDBC Manager connection.

BUSINESS INTELLIGENCE LABORATORY. Data Access: Relational Data Bases. Business Informatics Degree

MANTHLY TEST SEPTEMBER 2017 QUESTION BANK CLASS: XII SUBJECT: INFORMATICS PRACTICES (065)

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

Introduction. This course Software Architecture with Java will discuss the following topics:

UNIT-3 Java Database Client/Server

Advances in Programming Languages

Database Applications

JDBC. Sun Microsystems has included JDBC API as a part of J2SDK to develop Java applications that can communicate with databases.

Calling SQL from a host language (Java and Python) Kathleen Durant CS 3200

Pieter van den Hombergh. March 25, 2018

Server-side Web Programming

Introduction. Literature: Steelman & Murach, Murach s Java Servlets and JSP. Mike Murach & Associates Inc, 2003

Data Modelling and Databases. Exercise Session 7: Integrity Constraints

This lecture. Databases - JDBC I. Application Programs. Database Access End Users

Visit for more.

JDBC Drivers Type. JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server.

The Relational Model. Chapter 3

INSTITUTE OF AERONAUTICAL ENGINEERING (Autonomous) Dundigal, Hyderabad

Chapter 1 An introduction to relational databases and SQL

Slides by: Ms. Shree Jaswal

Database Applications (15-415)

Lecture 2. Introduction to JDBC

General Overview - rel. model. Carnegie Mellon Univ. Dept. of Computer Science Database Applications. Reminder: our Mini-U db

JDBC SHORT NOTES. Abstract This document contains short notes on JDBC, their types with diagrams. Rohit Deshbhratar [ address]

1. PhP Project. Create a new PhP Project as shown below and click next

Advances in Programming Languages

Chapter 2. DB2 concepts

CSE 308. Database Issues. Goals. Separate the application code from the database

CMPUT 391 Database Management Systems. JDBC in Review. - Lab 2 -

O ne of the most important features of JavaServer

Database Programming. Week 9. *Some of the slides in this lecture are created by Prof. Ian Horrocks from University of Oxford

PARTIAL Final Exam Reference Packet

Database Access with JDBC. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark

The Relational Model. Chapter 3. Comp 521 Files and Databases Fall

Basic SQL. Basic SQL. Basic SQL

DAVID M. KROENKE and DAVID J. AUER. DATABASE CONCEPTS, 7 th Edition. Chapter Seven. Database Processing Applications. Chapter Objectives

Assorted Topics Stored Procedures and Triggers Pg 1

Allenhouse Institute of Technology (UPTU Code : 505) OOT Notes By Hammad Lari for B.Tech CSE V th Sem

The Relational Model. Chapter 3. Comp 521 Files and Databases Fall

Relational Database Systems Part 01. Karine Reis Ferreira

Developing a Mobile Web-based Application with Oracle9i Lite Web-to-Go

3. The pool should be added now. You can start Weblogic server and see if there s any error message.

OWASP 5/07/09. The OWASP Foundation OWASP Static Analysis (SA) Track Session 1: Intro to Static Analysis

The Relational Model. Chapter 3. Database Management Systems, R. Ramakrishnan and J. Gehrke 1

Transcription:

Database Application Programs PL/SQL, Java and the Web As well as setting up the database and running queries, it is vital to be able to build programs which manage the database although they will only do so through the DBMS This needed to: provide a user interface impose constraints which SQL cannot manage program complex data manipulation Programs can be added to a database in several ways: having some kind of programming system inside the DBMS providing application building tools e.g. the Access Switchboard connecting a programming language to a database A Bit More SQL Assertions These are database-schema elements, like relations or views, which are defined by: CREATE ASSERTION <name> CHECK ( <condition> ); The condition is a boolean expression which may refer to any relation or attribute in the database schema Not present in Oracle or MySQL Example there must be more tutorial groups than students CREATE ASSERTION SanityCheck CHECK ( SELECT COUNT(*) FROM Tutorial <= SELECT COUNT(*) FROM Student ) Example no tutorial t group may have more than 20 members CREATE ASSERTION NoLargeGroups CHECK ( NOT EXISTS ( SELECT tutorial# FROM Tutorial GROUP BY tutorial# HAVING COUNT(*) > 20 ); MSc/Dip IT - ISD L21 Database Connections (513-536) 513 MSc/Dip IT - ISD L21 Database Connections (513-536) 514 A Bit More SQL Triggers A trigger specifies actions that are to be taken if the database gets into a particular state or if a particular event occurs, e.g. by use of data manipulation statements (update, insert or delete), by use of data definition commands (create, drop, etc.), or by general system or user actions (shutdown, logon, etc. ) They can be used to performs tasks such as generating derived columns, enforcing referential integrity, enforcing complex business rules, maintaining synchronous table replicates, etc. A trigger has three parts: the event that triggers the rule e.g. update or logoff the condition to be checked e.g. age less than 100 (note this part is optional, if doesn t appear the event always triggers the action) the action to be taken some SQL data manipulation operations Triggers can be made to execute either before or after the event Some Sample Triggers These triggers maintain a derived total salary column in the Department table note the keywords new and old to refer to the original and updated version of a record: create trigger Total_Salary1 after insert on Employee // every time a new Employee record is created when (new.deptno is not null) // if the dept number is available update Department D // add to the new emp s dept set D.totalSalary = D.totalSalary + new.salary where new.deptno = D.number create trigger Total_Salary2 after update of Salary on Employee // every an Emp s salary is changed when (new.deptno is not null) // if the dept number is available update Department D // replace old salary with new set DtotalSalary= D.totalSalary D.totalSalary + new.salary old.salary where new.deptno = D.number MSc/Dip IT - ISD L21 Database Connections (513-536) 515 MSc/Dip IT - ISD L21 Database Connections (513-536) 516

PL / SQL create trigger Total_Salary3 after update of deptno on Employee // when an Emp s dept is changed begin update Department D1 // add salary to new department set D1.totalSalary = D1.totalSalary + new.salaryy where new.deptno = D1.number update Department D2 // add salary to new department set D2.totalSalary = D2.totalSalary old.salary where old.deptno = D2.number end // like in Java create trigger Total_Salary4 after delete on Employee // when an Emp is removed from the database when (old.deptno is not null)// if the dept number is available update Department D // take away old salary set D.totalSalary = D.totalSalary + old.salary where new.deptno = D.number This is a programming language and system which manages data inside the database It allows SQL commands to be placed inside a program as in: declare number agevariable = 0; for j in 1..10 loop agevariable ibl :=... some calculation; l insert into mytable (id, age) values(j, agevariable ); end loop; commit; These can be put into procedures (like methods) to be repeatedly called MSc/Dip IT - ISD L21 Database Connections (513-536) 517 MSc/Dip IT - ISD L21 Database Connections (513-536) 518 Database Connections Interoperability Key Slide Originally a DBMS was used in isolation. It held all of the data centrally, provided multiple interfaces, multiple connections and all of the functionality to manage that data Increasingly, enterprises need to connect databases: to each other - since a single (perhaps merged or devolved) enterprise is likely to have several database systems that it uses to other applications, such as spreadsheets, which also manage data to the web We will now look at the techniques involved in: writing applications which span multiple relational database systems writing applications with embedded databases connecting a database to the web When writing a database application, there is an increasing need to make it independent of the underlying database system which it is using: i) for an in-house application in an enterprise in which more than one DBMS is in use ii) for a software house developing software of general use Relational systems with SQL provide a single model for data and so should provide good support for such general application development, But: i) the programming g interface to SQL varies ii) the functionality provided varies iii) the flavour of SQL varies iv) the system stem catalogue varies - e.g. domain names (varchar, text, t varchar2) v) some data is not in a database vi) DBMS vendors pride themselves on adding extra functionality MSc/Dip IT - ISD L21 Database Connections (513-536) 519 MSc/Dip IT - ISD L21 Database Connections (513-536) 520

Open Data Base Connectivity (ODBC) The solution is to provide a single Application Programmer's Interface (API) to relational systems and other data sources Microsoft s ODBC: provides a single API for sending SQL to a source of data, where an ODBC di driver is available ilbl to manage the interaction i between application i and ddata permits the source of data to be relational or not standardises the SQL grammar assumes a core set of functions, but allows others to be supported provides querying functions to determine the nature of the DBMS, the meta- data and the catalogue It is therefore possible to write a program which runs on top of a number of data sources unchanged ODBC Architecture The architecture comprises four levels: The application carries out the processing and sends ODBC class to submit SQL statements and retrieve results. The driver manager identifies calls which identify the particular database and load and unload drivers appropriately. A driver is a DBMS-specific collection of code which implements ODBC calls, transforming them into the local DBMS flavour of SQL. The calls are then submitted to the data source and the data is retrieved and returned to the application. A data source is a collection of data (usually a database) which the driver has the ability to query. Key Slide Application Driver Manager Driver Driver Driver Data Source Data Source Data Source However, it will still be easier to write the application if you know in advance what those data sources are rather than try to provide for anything that t might come up MSc/Dip IT - ISD L21 Database Connections (513-536) 521 Thus to get an application to use a database residing with a particular DBMS, a driver for the DBMS must be installed. MSc/Dip IT - ISD L21 Database Connections (513-536) 522 The Structure of an Application which Uses ODBC All ODBC applications have a similar structure: 1. An application begins by requesting and receiving a connection to a data source 2. Then it queries the data source for information about which facilities are actually available and how they are made available 3. It then allocates a statement handle in the context of the connection - this is a like a stream along which queries expressed as strings can be sent 4a. Having set up its local store, it sends SQL queries via statement handles to retrieve data and assign them to local variables 4b. Or (for updates), it sends the updates and checks the success of these by retrieving the number of rows affected 5. It processes these data, perhaps issuing more SQL calls to retrieve more data or update the data 6. It terminates the connection MSc/Dip IT - ISD L21 Database Connections (513-536) 523 ODBC and SQL Statements The execution of an SQL statement involves two phases: i) A plan for executing the query is made by the DBMS - preparation ii) The plan is carried out - execution The application can separate these two by preparing the query using one call and executing it with another. Re-using the query will then save performing the preparation phase for all but the first use. There are several different ways of building up SQL statements: t t i) They are entered in the program complete as a single string Query q = makequery( select name from Student where matric=12345 ); ii) They are built up gradually to become that complete string int matric =... code to get the number; Query q = makequery( select name from Student where matric= + matric); iii)they are parameterised, prepared and then only given the parameter just before execution Query q = makequery( select name from Student twhere matric =?"); //? = parameter q.bindparameter( 1, 12345 ); // 12345 if the first parameter value MSc/Dip IT - ISD L21 Database Connections (513-536) 524

Java and Databases The Student Application Key Slide Increasingly, applications on top of databases are being programmed in Java These slides are intended to illustrate how an application is programmed using ODBC through Java The package for this is called JDBC As a very simple example, we will assume the database is in Access and holds a table of student data, which looks like: Student( name: text, age: number, matric: number ) The next slide has most of an application which will print the student names MSc/Dip IT - ISD L21 Database Connections (513-536) 525 public class Student { String name; // one variable for each field int age; // used in the application int matric; public Student( ResultSet RS ) { name = RS.getString(1); g( // get the first column as a string age = RS.getInt(2); // get second column as an integer matric = RS.getInt( matric ); // can use column name instead System.out.println( name ); public class MainClass { public void main( String[] args ) // the next 2 lines are Access specific { Connection con =... // ugly DBMS specific code to make the connection Statement stmt = con.createstatement(); ResultSet RS = stmt.executequery( "select * from Student" ); while ( RS.next() ) // The next method makes RS point to the next record and { Student dummy = new Student( RS ); // returns false at the end MSc/Dip IT - ISD L21 Database Connections (513-536) 526 Notes The program has implemented a class Student which matches the table Student This will hold variables for as many columns as are required Each of these is retrieved using getint, getstring, etc. Database access is managed through a connection object This is created using getconnection Statements t t handles are then created in the context t of a connection, using createstatement SQL is executed by passing a string holding the query to the statement handle The query returns a result set which is a list of records This list is retrieved one at a time by while RS.next() getint, getstring etc. also work on RS, getting the field of the current row from a numbered column Java Database Applications An application written in Java is one good way of controlling a database You can write a nice GUI It also has all of the other packages which hcan be useful JDBC provides a solid way of accessing the database It is also the basis of two of the main ways of writing web sites which use databases: Servlets JSP MSc/Dip IT - ISD L21 Database Connections (513-536) 527 MSc/Dip IT - ISD L21 Database Connections (513-536) 528

Databases and the Web (See also Lecture 10) Web sites are increasingly dynamically generated Instead of consisting of a number of pure HTML pages with client-side scripts (static pages), the web site contains programs which generate HTML when they are requested The generating programs live on the server and: expect some parameterised input along with the request (usually generated by forms) produce a different HTML page depending on the parameter values usually, use the parameters to query a data source to get part of the content of the returned HTML page most often this data source will be a database and SQL will be used to manage the query The programs are either: HTML extended with server side scripts (JSP); or written in a programming language (C, PERL, Java) and produce HTML as output (Servlets) MSc/Dip IT - ISD L21 Database Connections (513-536) 529 A Typical Servlet public class lecturersvlt extends HTTPServlet { public void dopost(httpservletrequest req, HttpServletResponse res) Access to the Request and Response Messages { // First get an output stream to send stuff to the client PrintWriter out = res.getwriter(); Response is just and output stream out.println( println( <html><head> <html><head> </head>\n<body> </head>\n<body> ); // start of HTML String login = req.getparameter( login ); Get the login from a form String sql = select code, title, name from Course, Lecturer Note where login = + login + ; name must by login ResultSet data = stmt.executequery( sql ); Database query as a out.println( println( <h1>the Courses Given by + data.getstring( getstring("name") name + string </h1> <ul> ); // get the value of name for this record... while loop through the data set once for each course Data extracted from out.println( <li><a href= + data.getstring("code") +.html the record + data. getstring("title) + </a> </li> ); out.println( </ul></body></html> ); // end of HTML MSc/Dip IT - ISD L21 Database Connections (513-536) 530 JSP <% page language= java import= java.sql.* %> <% Connection DBcon = DriverMgr.getConnection( URL ); Stt Statement tstmt t= Dbcon.createStatement(); tstt t() String login = request.getparameter( login ); String sql = select code,title, name from Course, Lecturer where login = + login + ResultSet data = stmt.executequery( sql ); %> <html><head> </head> <body> <h1>the Courses Given by <%=data.getstring( getstring( name )%> name </h1> <ul> <% while data.next() {%> <li><a href= <%= data. getstring( code )%>.html > <%= data. getstring( title )%> </a></li> <%%> % // end of while loop </ul></body></html> MSc/Dip IT - ISD L21 Database Connections (513-536) 531 A Servlet for Inserting a Student into the Database public class addstudent extends HTTPServlet { public void dopost(httpservletrequest req, HttpServletResponse res) { PrintWriter out = res.getwriter(); // get output stream for HTML out.println( <html><head> </head>\n<body> ); // start of HTML String name = req.getparameter( name ); // age and matric similar String sql = insert into Student values( + // Build up insert statement name +, + age +, + matric + ) ; // from form variables ResultSet nrecords = executeupdate(sql); // returns number of records inserted if (nrecords == 0) out.println( <p>sorry insertion failed </p> ); // failure if nothing inserted else out.println( <p>record inserted</p> ); // success out.println( </ul></body></html> ); // end of HTML MSc/Dip IT - ISD L21 Database Connections (513-536) 532

variables all start $ PHP Connectivity with MySQL $Advisor = $POST[ Advisor ]; $db = mysql_connect( storo", "dymockvj", "4116") or die ("Could not connect"); mysql_select_db("dymockvj") or die ("Cannot select db"); Create a MySQL Connection Using database, dymockvj $query = "SELECT * FROM Student get the student records for this advisor WHERE advisor =.. $Advisor. ORDER BY Year, Name";. means string concatenation $result = mysql_query($query, query($query, $db) or die ("Error with query"); PHP and MySQL Notes This is a popular combination for building dynamic web sites It is cheap and efficient The previous slide contained most of a PHP page: It starts by retrieving the form variable, Advisor It then opens a database connection PHP has a set of methods for each major DBMS Again the query is a string $result is similar to a result set It uses a while loop again $row holds a record (as an array indexed by column name) while ($row = mysql _ fetch_ array($result)) { echo $row[ name"]..$row[ matric"]; loop once for each record output the student name and matric MSc/Dip IT - ISD L21 Database Connections (513-536) 533 MSc/Dip IT - ISD L21 Database Connections (513-536) 534 Other Tasks of the Server Side Programs As well as accessing the database and building up the HTML, the program must: deal with security ensure processes are as efficient as possible - example making connections is time consuming so making one up every time a user enters a site would be slow therefore, the site builds up a collection of connections when it is started t up and allocates a free one when the user logs in this is called connection pooling deal with sessions i.e. ensure that each min-program is connected to the whole by using thesamedata manage constraint violations etc. Security Example SQL Injection SQL Injection is a security attack which exploits poorly written server programs Example, a page contains a request for an age and then returns data about people of that age Inside the server program is the query: select * from Person where age = req.getparameter( age ) i.e. get what s entered in the agetextbox and use it but if someone enters this in the box: 23; delete from Person then the table will be destroyed MSc/Dip IT - ISD L21 Database Connections (513-536) 535 MSc/Dip IT - ISD L21 Database Connections (513-536) 536