Presentation is loading. Please wait.

Presentation is loading. Please wait.

JDBC™ Advanced Concepts

Similar presentations


Presentation on theme: "JDBC™ Advanced Concepts"— Presentation transcript:

1 JDBC™ Advanced Concepts
©SoftMoore Consulting

2 JDBC Advanced Concepts
Prepared Statements Use prepared statements when you are executing the same query/update with different values to reduce potential for SQL injection attacks Basic idea: A prepared statement is a parameterized query or update with placeholders for changing values. Advantages The prepared statement can be precompiled by the database, resulting in significantly faster runtime performance (but may not always be faster that plain statements – benchmark) Reduces opportunities for “hacking” when working with user data ©SoftMoore Consulting

3 Using Prepared Statements
JDBC Advanced Concepts Using Prepared Statements Prepared statements allow arguments (IN parameters) to be specified outside of statement are created using method Connection.prepareStatement() ? characters specify IN parameters whose values are supplied by setXXX() methods before the statement is executed Note: Parameters are numbered starting with 1! ©SoftMoore Consulting

4 Example: Prepared Statements
JDBC Advanced Concepts Example: Prepared Statements String query = "insert into author values (?, ?, ?)"; Connection conn = ...; // obtain a database connection PreparedStatement stmt = conn.prepareStatement(query); // Set values for parameters stmt.setInt(1, 1025); stmt.setString(2, "Gosling"); stmt.setString(3, "James"); int result = stmt.executeUpdate(); if (result != 1) throw new Exception("Bad Update"); ©SoftMoore Consulting

5 JDBC Advanced Concepts
Stored Procedures A stored procedure is a block of SQL code stored in the database and executed on the server. Accessed from Java through class CallableStatement Similar to prepared statements Exact syntax to create a stored procedure may differ among database vendors. Some databases support the use of Java for creating stored procedures. ©SoftMoore Consulting

6 Example: SQL for a Stored Procedure
JDBC Advanced Concepts Example: SQL for a Stored Procedure create procedure getDailyTotal @day int output as begin = sum (cups) from JoltData where day end ©SoftMoore Consulting

7 Example: Java Code to Create a Stored Procedure
JDBC Advanced Concepts Example: Java Code to Create a Stored Procedure stmt.execute ("create procedure getDailyTotal" + int output" + " as" + " begin" + " = sum (cups)" + " from JoltData" + " where day + " end"); Note: Database tools, not Java, are usually used to create stored procedures. ©SoftMoore Consulting

8 JDBC Advanced Concepts
Callable Statements Used to call a stored procedure Callable statements allow IN parameters, OUT parameters, INOUT parameters, and results are created using method Connection.prepareCall() ©SoftMoore Consulting

9 Example: Callable Statements
JDBC Advanced Concepts Example: Callable Statements CallableStatement cstmt = conn.prepareCall ("{call getDailyTotal (?, ?)}"); cstmt.setString(1, "Mon"); cstmt.registerOutParameter(2, java.sql.Types.INTEGER); cstmt.executeUpdate(); System.out.println("Total is " + cstmt.getInt(2)); ©SoftMoore Consulting

10 JDBC Advanced Concepts
Metadata Metadata is information about the structure of a database and its tables Examples the names of the tables the number of columns in a table the names of the columns in a table ©SoftMoore Consulting

11 Getting Information About the Database
JDBC Advanced Concepts Getting Information About the Database To access database metadata use the getMetaData() method in class Connection. Example Connection conn = DriverManager.getConnection ("jdbc:odbc:mydatasouce", "user", "password"); DatabaseMetaData md = conn.getMetaData(); Use DatabaseMetaData methods to get database information getDatabaseProductName() getMaxConnections() getTables() etc. ©SoftMoore Consulting

12 Getting Information About Tables
JDBC Advanced Concepts Getting Information About Tables Metadata is available with each ResultSet created by a query ResultSetMetaData meta = result.getMetaData(); Use ResultSetMetaData methods to get info about tables: getColumnCount() getColumnName(int i) getColumnTypeName(int i) etc. ©SoftMoore Consulting

13 Example: Using Metadata
JDBC Advanced Concepts Example: Using Metadata ResultSet rs = stmt.executeQuery("..."); ResultSetMetaData meta = rs.getMetaData(); int columns = meta.getColumnCount(); int numericCols = 0; for (int i = 1; i <= columns; ++i) { System.out.println(meta.getColumnLabel(i) + "\t" + meta.getColumnTypeName(i)); if (meta.isSigned(i)) // is it a signed number? numericCols++; } System.out.println ("Columns: " + columns + " Numeric: " + numericCols); ©SoftMoore Consulting

14 JDBC Advanced Concepts
Transactions A transaction is a set of SQL statements that, after having been executed, can then be committed or rolled back. If auto-commit mode is on, each statement is automatically committed after execution. Auto-commit is on by default . Use method setAutoCommit() (in class Connection) to change the default. ©SoftMoore Consulting

15 JDBC Advanced Concepts
Example: Transaction Connection conn = DriverManager.getConnection(…); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); stmt.executeUpdate("... SQL statement 1 … "); stmt.executeUpdate("... SQL statement 2 … "); stmt.executeUpdate("... SQL statement 3 … "); conn.commit(); // transaction (3 statements) // committed here ©SoftMoore Consulting

16 JDBC Advanced Concepts
Batch Updates A batch update is a set of multiple update statements that is submitted to the database for processing as a batch. Sending batch updates can, in some situations, be much more efficient than sending update statements separately Only commands that return an update count (e.g., INSERT, UPDATE, DELETE) or that return 0 (e.g., CREATE TABLE, DROP TABLE, ALTER TABLE) can be added to a batch update. ©SoftMoore Consulting

17 Example: Batch Updates
JDBC Advanced Concepts Example: Batch Updates conn.setAutoCommit(false); Statement stmt = conn.createStatement(); stmt.addBatch(insertQuery1); stmt.addBatch(insertQuery2); stmt.addBatch(insertQuery3); int[] updateCounts = stmt.executeBatch(); conn.commit(); conn.setAutoCommit(true); ©SoftMoore Consulting

18 JDBC Advanced Concepts
JDBC Exceptions Four types of JDBC exceptions: SQLException SQLWarning DataTruncation BatchUpdateException ©SoftMoore Consulting

19 JDBC Advanced Concepts
SQL Exceptions Superclass for all JDBC exceptions Multiple SQLException instances may be chained together Use method getNextException() to handle all SQLException objects. ... catch (SQLException ex) { while (ex != null) ex.printStackTrace(); ex = ex.getNextException(); } ©SoftMoore Consulting

20 Information Provided by SQL Exceptions
JDBC Advanced Concepts Information Provided by SQL Exceptions A descriptive String message A String containing the XOPEN SQL state A driver/source specific int for additional error reporting A link to the next exception in the chain ©SoftMoore Consulting

21 JDBC Advanced Concepts
SQL Warnings Subclass of SQLException SQLWarning instances are not thrown. Programmer must use getWarnings() method to retrieve them. Classes Connection, ResultSet, and Statement implement the getWarnings() method. Existing warnings are cleared out after every SQL call. ©SoftMoore Consulting

22 JDBC Advanced Concepts
Data Truncation Class DataTruncation is a subclass of SQLWarning. Indicates when information has been lost unexpectedly during a read or write A DataTruncation object is reported as a warning on a read truncation. A DataTruncation object is thrown as an exception on a write truncation. Use instanceof DataTruncation to check if a SQLWarning is a DataTruncation ©SoftMoore Consulting

23 Batch Update Exception
JDBC Advanced Concepts Batch Update Exception A BatchUpdateException is thrown by the executeBatch() method if one of the SQL statements you added to the batch produces a result set (usually a query), or one of the SQL statements in the batch does not execute successfully for some other reason. ©SoftMoore Consulting

24 Scrollable/Updateable Result Sets
JDBC Advanced Concepts Scrollable/Updateable Result Sets Result sets can be scrollable; i.e., the cursor can be moved in both forward and backward directions. Result sets can be updateable; i.e., you can update the current row or you can insert new rows Using a connection to create a scrollable result set Statement stmt1 = conn.createStatement(type, concurrency); PreparedStatement stmt2 = conn.createPreparedStatement (command, type, concurrency); The ResultSet type controls scrolling. The ResultSet concurrency controls updating. ©SoftMoore Consulting

25 JDBC Advanced Concepts
ResultSet Type Values TYPE_FORWARD_ONLY – result set is not scrollable TYPE_SCROLL_INSENSITIVE – result set is scrollable but not sensitive to database changes TYPE_SCROLL_SENSITIVE – result set is scrollable and sensitive to database changes ©SoftMoore Consulting

26 ResultSet Concurrency Values
JDBC Advanced Concepts ResultSet Concurrency Values CONCUR_READ_ONLY – result set cannot be used to update the database CONCUR_UPDATABLE – result set can be used to update the database ©SoftMoore Consulting

27 JDBC Advanced Concepts
Interface RowSet One problem with result sets is that you need to keep the connection open during the entire user interaction. The RowSet interface extends the ResultSet interface, but row sets don’t have to be tied to a database connection. Connected RowSet similar to ResultSet (connection must remain open) Disconnected RowSet more lightweight than a ResultSet object serializable ©SoftMoore Consulting

28 Using Row Sets As a JavaBeans component. All RowSets are JavaBean components; i.e., they have properties (fields with corresponding getter and setter methods) event notification (registered listeners are notified when certain events occur, such as cursor movement or row insert) For a connected RowSet: As a wrapper to make an otherwise non-scrollable and read-only ResultSet both scrollable and updatable. For a disconnected RowSet: Can be used for sending data over a network. It can even be used for sending data to thin clients such as mobile phones. ©SoftMoore Consulting

29 JDBC Advanced Concepts
RowSet Subinterfaces CachedRowSet disconnected caches its data in memory not suitable for very large data sets WebRowSet dicsonnected (extends CachedRowSet) can be saved to an XML file JDBCRowSet connected (maintains database connection) ©SoftMoore Consulting

30 Populating a CachedRowSet
JDBC Advanced Concepts Populating a CachedRowSet with an existing ResultSet ResultSet rs = ...; CachedRowSet crs = new CachedRowSetImpl(); ... crs.populate(rs); conn.close(); ... // use crs ©SoftMoore Consulting

31 Populating a CachedRowSet
JDBC Advanced Concepts Populating a CachedRowSet By letting the CachedRowSet establish the connection CachedRowSet crs = new CachedRowSetImpl(); crs.setURL(url); crs.setUsername(user); crs.setPassword(password); crs.setCommand(query); crs.execute(); // 1. establishes the connection // 2. issues the query // 3. populates the row set // 4. disconnects ... // use crs ©SoftMoore Consulting

32 Motivation: Database Connection Pooling
JDBC Advanced Concepts Motivation: Database Connection Pooling Calls to DriverManager’s getConnection() method can be very expensive in terms of the amount of time it takes to create the connection. Plus, the more connections there are to a database, the longer it takes to create a new connection. There are mutual exclusion problems with sharing connections in a multi-threaded environment. ©SoftMoore Consulting

33 Database Connection Pooling
JDBC Advanced Concepts Database Connection Pooling Basic Idea: Cache connections so that they can be reused. Get Connection Pool Empty? Create Connection yes no Get Connection from Pool Return Connection ©SoftMoore Consulting

34 Role of a Connection Pool
JDBC Advanced Concepts Role of a Connection Pool connection pool data base ... n connections max n simultaneous connections ©SoftMoore Consulting

35 JDBC Connection Pooling
JDBC Advanced Concepts JDBC Connection Pooling JDBC provides an API for connection pooling (PooledConnection and ConnectionPoolDataSource) From a programmer’s perspective, there is no API difference between standard connections and pooled connections. Pooled connections are used just like standard connections. When a pooled connection is closed, it is actually returned to the pool so that it is available for reuse. ©SoftMoore Consulting

36 JDBC Advanced Concepts
Data Sources The low-level database connection information such as the driver name and database url are often packaged in a DataSource. DataSource objects are usually obtained via the Java Naming and Directory Interface (JNDI). Using JNDI, the user needs to know only the name of the data source and how to access the JNDI server. The DataSource object is then used to obtain a connection to the database. ©SoftMoore Consulting

37 JDBC Advanced Concepts
Using a Data Source Context ctx = new InitialContext(); DataSource ds = (DataSource)ctx.lookup("jdbc/Accounts"); Connection conn = ds.getConnection(username, password); ©SoftMoore Consulting

38 Implementing a Data Source
JDBC Advanced Concepts Implementing a Data Source Implementation of a DataSource is usually performed by the database vendor or a third party, such as an application server vendor. A DataSource object may return a standard connection, but typically it supports additional functionality such as connection pooling and distributed transactions. Example Java application talks to a DataSource DataSource talks to a ConnectionPoolDataSource ©SoftMoore Consulting

39 Beyond JDBC: The Java Persistence API
JDBC Advanced Concepts Beyond JDBC: The Java Persistence API The Java Persistence API (JPA) uses annotations to provide object/relational mapping. A Java class annotated as an entity typically represents a table in a relational database, and each object of the class corresponds to a row in that table. Primary keys and relationships are also indicated by appropriate annotations on the entity class. Entities are managed by an entity manager, an instance of the javax.persistence.EntityManager class. creates and removes persistent entity instances finds entities by the entity’s primary key allows queries to be run on entities ©SoftMoore Consulting

40 JDBC Advanced Concepts
JPA Example @Entity public class Customer private long id; public Set<Order> getOrders() } JPA will use default values for table names and column names (e.g., table “CUSTOMER”). ©SoftMoore Consulting


Download ppt "JDBC™ Advanced Concepts"

Similar presentations


Ads by Google