1 / 20

JDBC Part II

Explore JDBC types, Statements versus PreparedStatements, NULL values, metadata usage, close() methods, exception handling, transactions, and ORM mappings for efficient Java-Database interactions. Learn about dealing with different SQL types, query procession methods, and managing transactions seamlessly.

jcallaghan
Download Presentation

JDBC Part II

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JDBC Part II CS 124

  2. More about JDBC • Types • Statement versus PreparedStatement • Timeout • NULL values • Meta-data • close() methods • Exceptions • Transactions • JDBC and ORM

  3. Mapping Java Typesto SQL Types SQL type Java Type CHAR, VARCHAR, LONGVARCHAR String NUMERIC, DECIMAL java.math.BigDecimal BIT boolean TINYINT byte SMALLINT short INTEGER int BIGINT long REAL float FLOAT, DOUBLE double BINARY, VARBINARY, LONGVARBINARY byte[] DATE java.sql.Date TIME java.sql.Time TIMESTAMP java.sql.Timestamp

  4. Date and time types • Times in SQL are notoriously non-standard • Java defines three classes to help • java.sql.Date • year, month, day • java.sql.Time • hours, minutes, seconds • java.sql.Timestamp • year, month, day, hours, minutes, seconds, nanoseconds • usually use this one

  5. Dealing with types • When processing a query (via executeQuery and ResultSet), you need to establish the correspondence between JDBC types and SQL types • Basis for getXXX() methods for a ResultSet • Good idea to also use setXXX() methods on a PreparedStatement • Versus building the query string manually

  6. Statement vs PreparedStatement • Are these the same? What do they do? String val = "abc"; Statement stmt = con.createStatement( ); ResultSet rs = stmt.executeQuery("select * from R where A=" + val); String val = "abc"; PreparedStatement pstmt = con.prepareStatement("select * from R where A=?"); pstmt.setString(1, val); ResultSet rs = pstmt.executeQuery();

  7. Statement vs PreparedStatement • This will result in an error • Resulting SQL is • select * from R where A=abc • missing the quotes String val = "abc"; Statement stmt = con.createStatement( ); ResultSet rs = stmt.executeQuery("select * from R where A=" + val);

  8. Statement vs PreparedStatement • This version is OK • Resulting SQL is • select * from R where A=‘abc’ • a PreparedStatement properly handles the data type • Useful particularly for difficult types like dates/times String val = "abc"; PreparedStatement pstmt = con.prepareStatement("select * from R where A=?"); pstmt.setString(1, val); ResultSet rs = pstmt.executeQuery();

  9. Statement vs PreparedStatement • Will this work? • No!!! A ‘?’ can only be used to represent a column value PreparedStatement pstmt = con.prepareStatement("select * from ?"); pstmt.setString(1, myFavoriteTableString);

  10. Timeout • Use setQueryTimeOut(int seconds) of Statement to set a timeout for the driver to wait for a statement to be completed • If the operation is not completed in the given time, an SQLException is thrown • What is it good for? • testing query performance

  11. NULL values • In SQL, NULL means the field is empty • Not the same as 0 or "" • In JDBC, you must explicitly ask if the last-read field was null • ResultSet.wasNull(column) • For example, getInt(column) will return 0 if the value is either 0 or NULL!

  12. NULL values • When inserting null values into placeholders of Prepared Statements: • Use the method setNull(index, Types.sqlType) for primitive types (e.g. INTEGER, REAL); • You may also use the set<Type>(index, null) for object types (e.g. STRING, DATE).

  13. ResultSet meta-data A ResultSetMetaData is an object that can be used to get information about the properties of the columns in a ResultSet object An example: write the columns of the result set ResultSetMetaData rsmd = rs.getMetaData(); int numcols = rsmd.getColumnCount(); for (int i = 1 ; i <= numcols; i++) { System.out.print(rsmd.getColumnLabel(i)+" "); }

  14. Calling close() on objects • Remember to close the Connections, Statements, Prepared Statements and Result Sets • Forgetting these can result in unpredictable results, though generally it results in an OutOfMemoryError if done too many times con.close(); stmt.close(); pstmt.close(); rs.close()

  15. Dealing With Exceptions • An SQLException is actually a list of exceptions catch (SQLException e) { while (e != null) { System.out.println(e.getSQLState()); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); e = e.getNextException(); } }

  16. Transactions and JDBC • Transaction: more than one statement that must all succeed (or all fail) together • e.g., updating several tables due to customer purchase • If one fails, the system must reverse all previous actions • Also can’t leave DB in inconsistent state halfway through a transaction • COMMIT = complete transaction • ROLLBACK = cancel all actions

  17. Example • Suppose we want to transfer money from bank account 13 to account 72: PreparedStatement pstmt = con.prepareStatement("update BankAccount set amount = amount + ? where accountId = ?"); pstmt.setInt(1,-100); pstmt.setInt(2, 13); pstmt.executeUpdate(); pstmt.setInt(1, 100); pstmt.setInt(2, 72); pstmt.executeUpdate(); What happens if this last update fails?

  18. Transaction Management • Transactions are not explicitly opened and closed • The connection has a state called AutoCommit mode • if AutoCommit is true, then every statement is automatically committed as they are executed • if AutoCommit is false, then every statement is added to an ongoing transaction • Default: true

  19. AutoCommit on Connection setAutoCommit(boolean val) • If you set AutoCommit to false, you must explicitly commit or rollback the transaction using Connection.commit() and Connection.rollback() • Note: DDL statements (e.g., creating/deleting tables) in a transaction may be ignored or may cause a commit to occur • The behavior is DBMS dependent

  20. JDBC usage in industry • JDBC as you can see is very cumbersome coding wise especially for systems with many queries and many tables • Over the years, Object Relational Mapping (ORM) software have been created to simplify the use of JDBC • generally, most externalize the mappings of JDBC table columns to java objects and provide simpler API for common CRUD operations • Some ORM software: • Apache iBatis (http://ibatis.apache.org/) • Hibernate (http://www.hibernate.org/)

More Related