JDBC Part II
-
Upload
valencia-cruz -
Category
Documents
-
view
25 -
download
1
description
Transcript of JDBC Part II
![Page 1: JDBC Part II](https://reader036.fdocuments.us/reader036/viewer/2022082817/56812b1c550346895d8f0f32/html5/thumbnails/1.jpg)
JDBC Part II
CS 124
![Page 2: JDBC Part II](https://reader036.fdocuments.us/reader036/viewer/2022082817/56812b1c550346895d8f0f32/html5/thumbnails/2.jpg)
More about JDBC
Types Statement versus PreparedStatement Timeout NULL values Meta-data close() methods Exceptions Transactions JDBC and ORM
![Page 3: JDBC Part II](https://reader036.fdocuments.us/reader036/viewer/2022082817/56812b1c550346895d8f0f32/html5/thumbnails/3.jpg)
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
![Page 4: JDBC Part II](https://reader036.fdocuments.us/reader036/viewer/2022082817/56812b1c550346895d8f0f32/html5/thumbnails/4.jpg)
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
![Page 5: JDBC Part II](https://reader036.fdocuments.us/reader036/viewer/2022082817/56812b1c550346895d8f0f32/html5/thumbnails/5.jpg)
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
![Page 6: JDBC Part II](https://reader036.fdocuments.us/reader036/viewer/2022082817/56812b1c550346895d8f0f32/html5/thumbnails/6.jpg)
Statement vs PreparedStatement
Are these the same? What do they do?
String val = "abc";
PreparedStatement pstmt = con.prepareStatement("select * from R where A=?");
pstmt.setString(1, val);
ResultSet rs = pstmt.executeQuery();
String val = "abc";
Statement stmt = con.createStatement( );
ResultSet rs =
stmt.executeQuery("select * from R where A=" + val);
![Page 7: JDBC Part II](https://reader036.fdocuments.us/reader036/viewer/2022082817/56812b1c550346895d8f0f32/html5/thumbnails/7.jpg)
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);
![Page 8: JDBC Part II](https://reader036.fdocuments.us/reader036/viewer/2022082817/56812b1c550346895d8f0f32/html5/thumbnails/8.jpg)
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();
![Page 9: JDBC Part II](https://reader036.fdocuments.us/reader036/viewer/2022082817/56812b1c550346895d8f0f32/html5/thumbnails/9.jpg)
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);
![Page 10: JDBC Part II](https://reader036.fdocuments.us/reader036/viewer/2022082817/56812b1c550346895d8f0f32/html5/thumbnails/10.jpg)
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
![Page 11: JDBC Part II](https://reader036.fdocuments.us/reader036/viewer/2022082817/56812b1c550346895d8f0f32/html5/thumbnails/11.jpg)
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!
![Page 12: JDBC Part II](https://reader036.fdocuments.us/reader036/viewer/2022082817/56812b1c550346895d8f0f32/html5/thumbnails/12.jpg)
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).
![Page 13: JDBC Part II](https://reader036.fdocuments.us/reader036/viewer/2022082817/56812b1c550346895d8f0f32/html5/thumbnails/13.jpg)
ResultSet meta-data
ResultSetMetaData rsmd = rs.getMetaData();
int numcols = rsmd.getColumnCount();
for (int i = 1 ; i <= numcols; i++) {
System.out.print(rsmd.getColumnLabel(i)+" ");
}
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
![Page 14: JDBC Part II](https://reader036.fdocuments.us/reader036/viewer/2022082817/56812b1c550346895d8f0f32/html5/thumbnails/14.jpg)
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()
![Page 15: JDBC Part II](https://reader036.fdocuments.us/reader036/viewer/2022082817/56812b1c550346895d8f0f32/html5/thumbnails/15.jpg)
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();
}
}
![Page 16: JDBC Part II](https://reader036.fdocuments.us/reader036/viewer/2022082817/56812b1c550346895d8f0f32/html5/thumbnails/16.jpg)
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
![Page 17: JDBC Part II](https://reader036.fdocuments.us/reader036/viewer/2022082817/56812b1c550346895d8f0f32/html5/thumbnails/17.jpg)
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?
![Page 18: JDBC Part II](https://reader036.fdocuments.us/reader036/viewer/2022082817/56812b1c550346895d8f0f32/html5/thumbnails/18.jpg)
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
![Page 19: JDBC Part II](https://reader036.fdocuments.us/reader036/viewer/2022082817/56812b1c550346895d8f0f32/html5/thumbnails/19.jpg)
AutoCommit on Connection
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
setAutoCommit(boolean val)
![Page 20: JDBC Part II](https://reader036.fdocuments.us/reader036/viewer/2022082817/56812b1c550346895d8f0f32/html5/thumbnails/20.jpg)
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/)