JDBC III IS 313 1.28.2003. Outline  Scrollable ResultSets  Updatable ResultSets  Prepared statements  Stored procedures.

Slides:



Advertisements
Similar presentations
MC365 JDBC and Server-Side Programming: Updating a database via JDBC & Connection Pooling.
Advertisements

Basic JDBC Celsina Bignoli What is JDBC Industry standard for database- connectivity between the Java language and a wide range of.
Database programming in Java An introduction to Java Database Connectivity (JDBC)
1 JDBC Java Database Connectivity. 2 c.pdf
Java Database Connectivity JDBC ICW Lecture 12 Errol Thompson.
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.
Three-Tier Architecture Oracle DB Server Apache Tomcat App Server Microsoft Internet Explorer HTML Tuples HTTP Requests JDBC Requests Java Server Pages.
JAVA JDBC JAVA JDBC Java Database Programming Lamiaa Said.
Java MS Access database connectivity Follow these steps: 1)Go to the start->Control Panel->Administrative Tools- > data sources. 2)Click Add button and.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Getting connected.  Java application calls the JDBC library.  JDBC loads a driver which talks to the database.  We can change database engines without.
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
CS178 Database Management “JDBC”. What is JDBC ? JDBC stands for “Java DataBase Connectivity” The standard interface for communication between a Java.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java/jsp program to connect to any database.
Beginning Databases with JDBC Mike Bradley Adapted from and notes by Kevin Parker, Ph.D.
Javax.sql and java.sql. java.sql Interface Connection public interface Connection extends WrapperWrapper A connection (session) with a specific database.
Databases: Queries with Java Dr Andy Evans. JDBC SQL Three methods: Statements: Standard, simple, SQL. PreparedStatements: Compiled SQL statements that.
 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(1/25) Database Programming with JDBC Keith Vander Linden.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 38 Advanced Java Database.
Dr R R DOCSIT, Dr BAMU. Basic Java : Introduction to JDBC 2 Objectives of This Session State what is Java Database Connectivity State different.
JDBC Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
Connecting to Oracle using Java November 4, 2009 David Goldschmidt, Ph.D. David Goldschmidt, Ph.D.
JDBC Java and Databases, including Postgress. JDBC l Developed by Industry leaders l Three main goals: –JDBC should be an SQL-level API –JDBC should capitalize.
Stored procedures1 Stored procedures and functions Procedures and functions stored in the database.
JDBC  The JDBC (Java Database Connectivity) API helps a Java program to access a database in a standard way  JDBC is a specification that tells the.
1 JDBC Aum Amriteshwaryai Namah. 2 2 JDBC – Java DataBase Connectivity.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 33 Advanced Java.
JDBC Enterprise Systems Programming. JDBC  Java Database Connectivity  Database Access Interface provides access to a relational database (by allowing.
JDBC Session 2 Tonight’s topics: 1.Prepared Statements 2.Transaction Processing 3.Callable Statements & Stored Procedures 4.Scrollable & Updatable Result.
Copyright  Oracle Corporation, All rights reserved. 6 Accessing a Database Using the JDBC API.
3-Tier Client/Server Internet Example. TIER 1 - User interface and navigation Labeled Tier 1 in the following graphic, this layer comprises the entire.
DAT602 Database Application Development Lecture 9 Advanced JDBC 2.
Copyright © 2002 ProsoftTraining. All rights reserved. Building Database Client Applications Using JDBC 2.0.
Web Design & Development 1 Lec Web Design & Development 2 More on JDBC.
Chapter 17 Accessing Databases with JDBC. JDBC JDBC provides a standard library for accessing relational databases. By using the JDBC API, you can access.
Creating competitive advantage Copyright © 2003 Enterprise Java Beans Presenter: Wickramanayake HMKSK Version:0.1 Last Updated:
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.
COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction.
1 Session 2 Module 3: Scrollable Resultset and Rowsets.
JDBC IV IS Outline  Quiz 1  Stored procedures  Batch processing  Transactions  Homework #2.
JDBC and SQLJ CIS 612 Spring JDBC JDBC is an API that enables database access from Java programs JDBC for DB access provides ◦ Portability across.
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
Adv Java Chapter 1.JDBC Chapter 2.Servlets Chapter 3.JSP.
JDBC - Resultset The java.sql.ResultSet interface represents the result set of a database query. A ResultSet object maintains a cursor that points to the.
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.
1 JDBC – Java Database Connectivity CS , Spring 2010.
JDBC I IS Why do we have databases?
JSP/Database Connectivity Instructor: Dr. M. Anwar Hossain.
Java Database Connectivity JDBC. Open Database Connectivity developed by Microsoft to provide interaction with databases using SQL. Use the JDBC-ODBC.
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.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
JDBC IV IS Outline  Batch processing  Transactions  Homework #2  Examples.
Database: JDBC Overview
JDBC – Java Database Connectivity
JDBC III IS
CS320 Web and Internet Programming Database Access with JDBC
Database JDBC Overview CS Programming Languages for Web Applications
HW#4 Making Simple BBS Using JDBC
Prof: Dr. Shu-Ching Chen TA: Sheng Guan
Database Programming Using JDBC and MySQL C API
JDBC Example.
JDBC II IS
Presentation transcript:

JDBC III IS

Outline  Scrollable ResultSets  Updatable ResultSets  Prepared statements  Stored procedures

Scrollable / Updatable ResultSets

Cursors  bundle of information captures the current state of interaction with a database  cursor types simplest = forward-only otherwise tradeoff  flexibility / power  speed / server resources

JDBC Cursor Types  Two parameters ResultSet type ResultSet concurrency

ResultSet Type  Two dimensions forward-only vs scrollable insensitive vs sensitive  But forward-only = insensitive  Three possibilities forward-only scrollable, sensitive scrollable, insensitive

ResultSet Concurrency  Updatable Can the ResultSet be used to modify the database?  Two possibilities read-only updatable

JDBC Cursors

Using ResultSet Types  Statement RS types are assigned to a Statement ResultSet created by that Statement will have the given properties Statement stmt = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = stmt.executeQuery (querySQL);

Scrollable ResultSet  Can move both directions in results  Can jump around  Methods previous () absolute () relative () last () first ()  Note not subclass of ResultSet

Sensitive vs Insensitive  If insert happens first, query will return new row  If select happens first? insensitive cursor will not return new row sensitive cursor will/should return new row

Updatable ResultSet  Use results of SELECT query perform INSERT, DELETE, and UPDATE  Useful for interactive DB editing

Update Process 1. Connect to database 2. Create an updatable statement 3. Call executeQuery to get ResultSet 4. Navigate to a row 5. Call update methods to modify contents 6. Call updateRow () to commit changes

Update Methods  Examples rs.updateString (1, “Jack”); rs.updateDate (“Arrival_Date”, m_date);  Like “get” methods update[Type_name] always the Java type column name or number new value

Example public void upgradeRoom (String firstName, String lastName) { Statement dateStmt = conn.createStatement ( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = dateStmt.executeQuery ( “SELECT * FROM Reservations WHERE (FirstName=‘” + firstName + “’) AND (LastName=‘” + lastName + “’));”); if (rs.next()) { int roomType = rs.getInt (“Room_Type”); if (roomType < MAXIMAL_ROOM_TYPE) { rs.updateInt ("Reservation_Count", roomsOfType + 1); rs.updateRow (); } rs.close (); }

Inserting  Insert Row Separate location for insertion

Insertion Process 1. Connect to database 2. Create an updatable statement 3. Call executeQuery to get ResultSet 4. Move to the insert row 5. Call update methods to fill row 6. Call insertRow to commit changes 7. Continue inserting or Move back to other results

Example Statement stmt = conn.createStatement ( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = stmt.executeQuery (“SELECT * FROM Capacity”); rs.moveToInsertRow (); rs.updateDate ("Date", DBUtilities.dateToSQLDate(m_date)); rs.updateInt ("Room_Type", m_roomType); rs.updateInt ("Reservation_Count", 1); rs.insertRow (); rs.close ();

Delete  Simple rs.deleteRow ();

Updates vs SQL Statement stmt = conn.createStatement ( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = stmt.executeQuery ( “SELECT * FROM Books WHERE (Publisher=‘MS Press’);”); while (rs.next()) { double price = rs.getDouble (“Price”); rs.updateDouble (“Price”, price * 0.9); rs.updateRow (); } Or Statement stmt = conn.createStatement (); ResultSet rs = stmt.executeQuery ( “UPDATE Books SET Price=(Price*0.9) WHERE (Publisher=‘MS Press’);”);

Summary – Updatable ResultSet  Use Updatable RS instead of INSERT, UPDATE and DELETE  Benefits integrates with querying single SQL expression  But SQL may be more efficient

Prepared Statements

Query Answering Process 1. Parse SQL string 2. Construct a query plan 3. Execute plan 4. Deliver results

Efficiency Gains?  Steps 1 & 2 will be similar for similar queries  Programs often issue many similar queries empirical fact  String manipulation is slow

Example public void upgradeRoom (String firstName, String lastName) { Statement dateStmt = conn.createStatement ( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = dateStmt.executeQuery ( “SELECT * FROM Reservations WHERE (FirstName=‘” + firstName + “’) AND (LastName=‘” + lastName + “’));”); if (rs.next()) { int roomType = rs.getInt (“Room_Type”); if (roomType < MAXIMAL_ROOM_TYPE) { rs.updateInt ("Reservation_Count", roomsOfType + 1); rs.updateRow (); } rs.close (); }

Repeated Costs  String assembly  SQL Parsing identical queries the same except for names  Query planning probably identical depends on exact structure of indices  Standard computational solution do the work once cache the result

Maintenance Problems  Hard to verify / debug the SQL  Hard to modify the query

Prepared Statement  SQL statement with parameters  Parameters filled programmatically not with string operations

Find By Name SELECT * FROM Reservations WHERE (FirstName=‘” + firstName + “’) AND (LastName=‘” + lastName + “’));”

Prepared Statement “SELECT * FROM Reservations WHERE (FirstName=?) AND (LastName=?));”

Prepared Statements in JDBC PreparedStatement stmt = con.prepareStatement ( “SELECT * FROM Reservations WHERE (FirstName=?) AND (LastName=?));”); stmt.setString (1, “Jack”); stmt.setString (2, “Spratt”); rs = stmt.executeQuery();

Steps 1. Call prepareStatement with parameterized SQL String 2. Set parameters values using setter methods setXxx (index, value)  parameters are numbered from 1! 3. Call executeQuery or executeUpdate no arguments

Summary – Prepared Statement  Use parameterized SQL instead of assembling queries with Strings  benefits much easier to read / maintain significant performance gain for multiple queries standard practice in JDBC coding

Stored Procedures

2-Tier Application

Where to put computation?  All client use database just to store copy to client to compute  All server use client just to display use database for computation

Client-Server Trade-off Data smallData large Server available Either OKServer Server busy ClientIt depends

Stored Procedures  Database-resident code  Serve many purposes computations too complex for SQL triggers move computation to the data

Steps 1. Write stored procedure 2. Create a callable statement 3. Set the parameters 4. Call the procedure 5. Possibly get return values

Java Stored Procedure (Oracle) public static void updateAvailableRoomData (int hotelId, String roomType, int mumOfRooms, String updateFlag) { Connection connection = null; // Database Connection Object try { connection = new OracleDriver().defaultConnection(); String addBookedSeats = " + "; String subTotalSeats = " - "; if (updateFlag.equals("COUT")) { addBookedSeats = " - "; subTotalSeats = " + "; } if (roomType.equals("ORCL")) roomType = "OTHR"; PreparedStatement pstmt = connection.prepareStatement("UPDATE ROOM_AVAILABILITY " + " SET BOOKED_" + roomType + " = BOOKED_" + roomType + addBookedSeats + mumOfRooms + ", TOTAL_" + roomType + " = TOTAL_" + roomType + subTotalSeats + mumOfRooms + " WHERE HOT_ID = ? AND BOOKING_DATE = " + " ( SELECT MAX(BOOKING_DATE) FROM ROOM_AVAILABILITY " + " WHERE HOT_ID = ? )" ); pstmt.setInt(1,hotelId); // Bind the Hotel ID input parameter pstmt.setInt(2,hotelId); // Bind the Hotel Id input parameter int noRecordsUpdated = pstmt.executeUpdate(); // Execute the Statement … et cetera …

From client CallableStatement stmt = con.prepareCall (“Call Hotel_HotelBookingsSample_updateAvailableRoomData (?,?,?,?)”); stmt.setInt (1, 5); stmt.setString (2, “Single”); stmt.setInt (3, 1); stmt.setString (4, “COUT”); stmt.execute();

Return values? stmt.registerOutParameter (3, Types.INTEGER); stmt.execute(); int result = Stmt.getInt(3);

Summary – Stored Procedures  Embed computation in database using database-specific code  benefits move computation to data  drawbacks SP code not portable maintenance problematic  still frequently used for performance benefits

JDBC Classes