1 Sub-queries and Views. 2 A Complex Query We would like to create a table containing 3 columns: –Sailor id –Sailor age –Age of the oldest Sailor How.

Slides:



Advertisements
Similar presentations
1 Advanced SQL Queries. 2 Example Tables Used Reserves sidbidday /10/04 11/12/04 Sailors sidsnameratingage Dustin Lubber Rusty.
Advertisements

19 augustus 2003augustus 2003 JSP-2. BICT 2JDBC BICT 3Install MySQL Download MySQL daemon – Free – Windows version… Start Daemon – Mysqld-nt.exe Download.
Basic JDBC Celsina Bignoli What is JDBC Industry standard for database- connectivity between the Java language and a wide range of.
JDBC. Java Database Connectivity (JDBC) Use the java.sql package to query and update the database. JDBC is an API that allows java to communicate with.
1 JDBC Java Database Connectivity. 2 c.pdf
1 JDBC: Java Database Connectivity. 2 Introduction to JDBC JDBC is used for accessing databases from Java applications Information is transferred from.
1 Views and Null values. 2 What does this return? SELECT B.bid, COUNT(*) FROM Boats B, Reserves R WHERE R.bid=B.bid and B.color=‘red’ GROUP BY B.bid For.
מסדי נתונים תשס " ג 1 JDBC Java Database Connectivity קורס מסדי נתונים.
1 JDBC – Java Database Connectivity. 2 Introduction to JDBC JDBC is used for accessing databases from Java applications Information is transferred from.
Java Database Connectivity (JDBC) java.sql package to query and update the database. JDBC is an API that allows java to communicate with a database server.
1 Rewriting Minus Queries Using Not In SELECT S.sname FROM Sailors S, Boats B, Reserves R WHERE S.sid = R.sid and R.bid = B.bid and B.color = ‘red’ MINUS.
1 Rewriting Intersect Queries Using In SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid = R.sid and R.bid = B.bid and B.color = ‘red’ INTERSECT.
1 JDBC – Java Database Connectivity Representation and Management of Data on the Internet.
Three-Tier Architecture Oracle DB Server Apache Tomcat App Server Microsoft Internet Explorer HTML Tuples HTTP Requests JDBC Requests Java Server Pages.
1 Triggers. 2 PL/SQL reminder We presented PL/SQL- a Procedural extension to the SQL language. We reviewed the structure of an anonymous PL/SQL block:
1 JDBC "Java Database Connectivity". 2 Getting Started Guide: etstart/GettingStartedTOC.fm.html java.sql.
UFCE4Y UFCE4Y-20-3 Components and Services Julia Dawson.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
1 CSC 440 Database Management Systems JDBC This presentation uses slides and lecture notes available from
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java/jsp program to connect to any database.
1 JDBC – Java Database Connectivity Modified slides from Dr. Yehoshua Sagiv.
Web Design & Development 1 Lec Web Design & Development 2 More on JDBC.
JDBC Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
1 JDBC – Java Database Connectivity. 2 Introduction to JDBC JDBC is used for accessing databases from Java applications Information is transferred from.
1 JDBC Aum Amriteshwaryai Namah. 2 2 JDBC – Java DataBase Connectivity.
JDBC Enterprise Systems Programming. JDBC  Java Database Connectivity  Database Access Interface provides access to a relational database (by allowing.
Chapter 8 Databases.
COMP201 Java Programming Topic 15: Database Connectivity JDBC Reading: Chapter 4, Volume 2.
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
Copyright  Oracle Corporation, All rights reserved. 6 Accessing a Database Using the JDBC API.
Java Database Connectivity. Java and the database Database is used to store data. It is also known as persistent storage as the data is stored and can.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
JDBC CS 124. JDBC Java Database Connectivity Database Access Interface provides access to a relational database (by allowing SQL statements to be sent.
Li Tak Sing COMPS311F. Database programming JDBC (Java Database Connectivity) Java version of ODBC (Open Database Connectivity) ODBC provides a standard.
JDBC Part II CS 124. More about JDBC Types Statement versus PreparedStatement Timeout NULL values Meta-data close() methods Exceptions Transactions JDBC.
JDBC (Java Database Connectivity)
Database Management Systems 1 Raghu Ramakrishnan Database Application Development Chpt 6 Xin Zhang.
Advanced Java Session 5 New York University School of Continuing and Professional Studies.
Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC.
Umair Javed©2005 Enterprise Application Development Java Database Connectivity (JDBC) JDBC1.
Introduction to JDBC Instructor: Mohamed Eltabakh 1.
1 JDBC: Java Database Connectivity. 2 Introduction to JDBC JDBC is used for accessing databases from Java applications Information is transferred from.
1 JDBC – Java Database Connectivity CS , Spring 2010.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
CS422 Principles of Database Systems JDBC and Embedded SQL Chengyu Sun California State University, Los Angeles.
JDBC Statements The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enables to send SQL or PL/SQL.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java program to connect to any database.
JDBC 2 Getting Started Guide: etstart/GettingStartedTOC.fm.html java.sql Package API:
1 JDBC – Java Database Connectivity THETOPPERSWAY.COM.
1. Writing a Java program to connect to SQL Server 2008 and Create a table Populate the table (insert data) Perform queries to retrieve information from.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
CS3220 Web and Internet Programming Database Access with JDBC
Java Access to RDB Relational databases (RDBs) dominate today, due to:
Lec - 14.
JDBC
JDBC – Java Database Connectivity
CS320 Web and Internet Programming Database Access with JDBC
JDBC – Java Database Connectivity
JDBC – Java Database Connectivity
HW#4 Making Simple BBS Using JDBC
Prof: Dr. Shu-Ching Chen TA: Sheng Guan
JDBC – Java Database Connectivity
קורס קבצים ובסיסי נתונים
Bolat Azamat, Kim Dongmin
JDBC Example.
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Database Application Development
Java Chapter 6 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

1 Sub-queries and Views

2 A Complex Query We would like to create a table containing 3 columns: –Sailor id –Sailor age –Age of the oldest Sailor How can this be done?

3 Attempt 1 SELECT S.sid, S.age, MAX(S.age) FROM Sailors S; Why is this wrong?

4 Attempt 2 SELECT S.sid, S.age, MAX(S.age) FROM Sailors S GROUP BY S.name, S.age; Why is this wrong?

5 Solution 1: Sub-query in FROM SELECT S.sid, S.age, M.mxage FROM Sailors S,(SELECT MAX(S2.age) as mxage FROM Sailors S2) M; We can put a query in the FROM clause instead of a table The query in the FROM clause must be renamed with a range variable (M in this case).

6 Solution 1: Sub-query in SELECT SELECT S.sid, S.age, (SELECT MAX(S2.age) FROM Sailors S2) FROM Sailors S; A query in the SELECT clause must return at most one value for each row returned by the outer query.

7 Another Example of a Sub-query in SELECT SELECT S.sid, S.age, (SELECT MAX(S2.age) FROM Sailors S2 WHERE S2.age<S.age) FROM Sailors S; This query returns for each sailor the age of the oldest sailor that is younger than him. Note the use of S (defined in the outer query) within the inner query.

8 Another Example of a Sub-query in FROM?? SELECT S.sid, S.age, M.mxage FROM Sailors S, (SELECT MAX(S2.age) as mxage FROM Sailors S2 WHERE S2.age<S.age); Why is this wrong?

9 Solution 3: Views A View is a query that looks like a table and can be used as a table. CREATE OR REPLACE VIEW MaxAge as SELECT MAX(S.age) as mxage FROM Sailors S; SELECT S.sid, S.age, M.mxage FROM Sailors S, MaxAge M;

10 Another Example of a View CREATE OR REPLACE VIEW MaxAges as SELECT S1.sid, S2.age as mxage FROM Sailors S1, Sailors S2 WHERE S2.age = (SELECT MAX(S3.age) FROM Sailors S3 WHERE S3.age < S1.age); SELECT S.sid, S.age, M.mxage FROM Sailors S, MaxAges M WHERE S.sid = M.sid;

11 Views For Restricting Access Suppose that we have a table: Grades(Login, Exercise, Grade) We would like a user to only be able to see his own grades. We create the following view and grant privileges to query the view (not the underlying table) CREATE OR REPLACE VIEW UserGrades as SELECT * FROM Grades WHERE Login = User; Pseudo-column which is equal to the user name.

12 Delete and Update

13 Deleting Tuples The basic form of a delete statement is: DELETE FROM TableName WHERE Condition;

14 Examples DELETE FROM Sailors WHERE rating < 3; DELETE FROM Sailors S1 WHERE S1.rating = (SELECT MIN(S2.rating) FROM Sailors S2) Delete Sailors with rating less than 3: Delete Sailors with the minimum rating:

15 Updating Tuples The basic form of an update statement is: UPDATE TableName SET Column1 = Value1, … ColumnN = ValueN WHERE Condition;

16 Example UPDATE Boats SET color = ‘red’, bname = ‘Voyager’ WHERE bid = 13; Update boat 13: color to red and name to voyager

17 Another Example UPDATE Sailors SET rating = (SELECT MAX(rating) FROM Sailors) WHERE sname = ‘Rusty’; Update rating of Rusty to be the maximum rating of any sailor Note: When updating with a subquery, the subquery must return one value only!

18 Connecting to a Database with JDBC

19 Why Access a Database with Java? There are queries that can not be computed in Sql: –Given a table Bus(Source, Destination) find all pairs of places that it is possible to travel (paths of any length Java allows for a convenient user interface to the database

20 Learning JDBC On the Tirgul page of the Online Resources of the course homepage I will put: –A link to a JDBC tutorial –A link to the JDBC API –Several Example Programs

21 Packages to Import In order to connect to the Oracle database from java, import the following packages: –java.sql.*; –oracle.jdbc.driver.*;

22 Connecting to the Database DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); String driver = "jdbc:oracle:thin:"; String user = "sam"; String password = "samIam"; String conStr = driver + user + “/” + password + Connection con = DriverManager.getConnection(conStr);

23 Accessing the Database The database is accessed using the Connection object. 3 Types of statements are possible: –Statement –PreparedStatement –CallableStatement (not discussed today) Note that CallableStatement inherits from PreparedStatement which inherits from Statement

24 Querying with Statement String queryStr = "SELECT * FROM Member " + "WHERE Lower(Name) = 'harry potter'"; Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(queryStr); Statements are used for queries that are only used once. The executeQuery method returns an object representing the query result.

25 Changing DB with Statement String deleteStr = “DELETE FROM Member " + "WHERE Lower(Name) = ‘lord voldemort’"; Statement stmt = con.createStatement(); int delnum = stmt.executeUpdate(deleteStr); executeUpdate is used for data manipulation: insert, delete, update, create table, etc. executeUpdate returns the number of rows modified.

26 Querying with PreparedStatement String queryStr = "SELECT * FROM Program " + "WHERE Name = ? and Cost < ?”; PreparedStatement pstmt = con.prepareStatement(queryStr); pstmt.setString(1, “Unfogging the Future”); pstmt.setInt(2, 1000); ResultSet rs = pstmt.executeQuery();

27 About Prepared Statements Prepared Statements are used for queries that are executed many times. They are parsed only once. Using setString(i, value) (setInt(i, value), etc.) the i-th question mark is set to the given value.

28 Changing DB with PreparedStatement String deleteStr = “DELETE FROM Program " + "WHERE Name = ? and Cost < ?”; PreparedStatement pstmt = con.prepareStatement(deleteStr); pstmt.setString(1, “Unfogging the Future”); pstmt.setInt(2, 1000); int delnum = pstmt.executeUpdate();

29 Printing Query Output: Result Set (1) ResultSetMetaData rsmd = rs.getMetaData(); int numcols = rsmd.getColumnCount(); for (int i = 1 ; i <= numcols; i++) { if (i > 1) System.out.print(","); System.out.print(rsmd.getColumnLabel(i)); } Print Column Headers:

30 Printing Query Output: Result Set (2) while (rs.next()) { for (int i = 1 ; i <= numcols; i++) { if (i > 1) System.out.print(","); System.out.print(rs.getString(i)); } System.out.println(""); } To get the data in the i-th column: rs.getString(i) To get the data in column Url: rs.getString(“Url”)

31 Cleaning Up After Yourself Remember to close the Connections, Statements and ResultSets con.close(); stmt.close(); rs.close()

32 Dealing With Exceptions A exception can have more exceptions in it. catch (SQLException e) { while (e != null) { System.out.println(e.getSQLState()); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); e = e.getNextException(); }