SQL and Java | slide # 1 |
...JDBC | slide # 2 |
...JDBC Architecture | slide # 2 |
...Using JDBC | slide # 4 |
......Outline | slide # 4 |
......Loading a Driver | slide # 4 |
......Connecting to a Database | slide # 6 |
......Issue Queries and Receive Results | slide # 8 |
......ResultSet - Result of a Query | slide # 10 |
......SQL Data Types and Java | slide # 11 |
......Statement Methods | slide # 12 |
......Connection Methods | slide # 12 |
......Transactions | slide # 13 |
......PreparedStatement | slide # 15 |
......CallableStatement | slide # 17 |
......DatabaseMetaData | slide # 17 |
Client/Server Programming with Java and CORBA, Orfali and Harkey, John Wiley and Sons, Inc. 1997
SQL Call Level Interface (CLI) is the SAG standard for connecting remotely to a database from a program
CLI uses a driver which connects to the database
Program uses a driver manager to talk to the driver
The driver is database specific
In 1994 X/Open adopted SQL CLI to produce X/Open CLI
In 1996 X/Open CLI was adapted by ISO to become ISO 9075-3 Call level Interface
Microsoft's Open Database Connectivity (ODBC) is an
extensions of the SAG CLI
ODBC 2.0 (32 bit) has three conformance levels
Sun also states that some people think JDBC is an abbreviation for Java Database Connectivity
JDBC is a portable SQL CLI written in Java.
Like all CLIs, JDBC does not replace or extend SQL, it just allows your program to make SQL calls to a database
Most references claim JDBC is easier to use/understand than ODBC
Interfaces | Classes |
CallableStatement | Date |
Connection | DriverManager |
DatabaseMetaData | DriverPropertyInfo |
Driver | Time |
PreparedStatement | Timestamp |
ResultSet | Types |
ResultSetMetaData | |
Statement |
To load the Oracle driver
import java.sql.*; class JdbcTest { public static void main (String args []) throws ClassNotFoundException { Class.forName ("oracle.jdbc.OracleDriver"); } }
This requires that oracle package be in your path
A properly written driver will register itself with the
DriverManager class
getLoginTimeout()
setLoginTimeout(int)
import java.sql.*; class JdbcTest { static String ARS_URL = "jdbc:oracle:@PutDatabaseNameHere"; public static void main (String args []) throws SQLException, ClassNotFoundException { Class.forName ("oracle.jdbc.OracleDriver"); Connection ARS; ARS =DriverManager.getConnection(ARS_URL, "whitney", "secret"); } }
<subprotocol> is usually the driver or database connectivity mechanism
<subname> depends on the <subprotocol>, can vary with vender
<subname> can include Internet address for remote
databases
static String ARS_URL = "jdbc:oracle:@PutDatabaseNameHere"; DriverManager.getConnection(ARS_URL, "whitney","secret");
DriverManager.getConnection( "jdbc:oracle:whitney/secret@PutDatabaseNameHere");
java.util.Properties info = new java.util.Properties(); info.addProperty ("user", "whitney"); info.addProperty ("password","secret"); DriverManager getConnection (ARS_URL ,info );
import java.sql.*; import java.io.*; class JdbcTest { static String ARS_URL = "jdbc:oracle:@PutDatabaseNameHere"; public static void main (String args []) throws SQLException, ClassNotFoundException, IOException { Class.forName ("oracle.jdbc.OracleDriver"); Connection ARS; ARS =DriverManager.getConnection(ARS_URL, "whitney", "secret"); Statement schedule = ARS.createStatement (); String flightOut = "SELECT * FROM AirlineSchedule WHERE from = SAN"; ResultSet fromSanDiego = schedule.executeQuery (flightOut); while ( fromSanDiego.next() ) { System.out.println (fromSanDiego.getString ("to")); } } }
AirlineSchedule | |||||
From | To | Depart Time | Arrival Time | Flight number | Aircraft type |
AMS | LAX | 04:15 | 15:15 | 602 | C |
DE | DFW | 9:00 | 11:30 | 1201 | B |
DE | DFW | 12:00 | 14:30 | 1202 | B |
DE | DFW | 16:00 | 18:30 | 1203 | B |
DE | FAR | 10:12 | 12:12 | 902 | A |
etc. |
getAsciiStream(int) | getDate(int) | getObject(int) |
getBigDecimal(int,int) | getDouble(int) | getShort(int) |
getBinaryStream(int) | getFloat(int) | getString(int) |
getBoolean(int) | getInt(int) | getTime(int) |
getByte(int) | getLong(int) | getTimestamp(int) |
getBytes(int) | getMetaData() | getUnicodeStream(int) |
clearWarnings() | getCursorName() | wasNull() |
close() | getWarnings() | |
findColumn(String) | next() |
SQL type | Java type |
CHAR | String |
VARCHAR | String |
LONGVARCHAR | String |
NUMERIC | java.math.BigDecimal |
DECIMAL | java.math.BigDecimal |
BIT | boolean |
TINYINT | byte |
SMALLINT | short |
INTEGER | int |
BIGINT | long |
REAL | float |
FLOAT | double |
DOUBLE | double |
BINARY | byte[] |
VARBINARY | byte[] |
LONGVARBINARY | byte[] |
DATE | java.sql.Date |
TIME | java.sql.Time |
TIMESTAMP | java.sql.Timestamp |
cancel() | getQueryTimeout() |
clearWarnings() | getResultSet() |
close() | getUpdateCount() |
execute(String) | getWarnings() |
executeQuery(String) | setCursorName(String) |
executeUpdate(String) | setEscapeProcessing(boolean) |
getMaxFieldSize() | setMaxFieldSize(int) |
getMaxRows() | setMaxRows(int) |
getMoreResults() | setQueryTimeout(int) |
clearWarnings() | isReadOnly() |
close() | nativeSQL(String) |
commit() | prepareCall(String) |
createStatement() | prepareStatement(String) |
getAutoCommit() | rollback() |
getCatalog() | setAutoCommit(boolean) |
getMetaData() | setCatalog(String) |
getTransactionIsolation() | setReadOnly(boolean) |
getWarnings() | setTransactionIsolation(int) |
isClosed() |
A transaction ends when a commit or rollback is sent
Connections are opened in auto commit mode:
What happens to data that is changed in a transaction, but not yet committed?
Can other programs access the old or new values?
Use setTransactionIsolation(int) in Connection class to set access levels
Access levels are given as static fields of Connection class
TRANSACTION_NONE
TRANSACTION_READ_COMMITTED
TRANSACTION_READ_UNCOMMITTED
TRANSACTION_REPEATABLE_READ
TRANSACTION_SERIALIZABLE
Transaction Example
import java.sql.*; import java.io.*; class JdbcTest { static String ARS_URL = "jdbc:oracle:@PutDatabaseNameHere"; public static void main (String args []) throws SQLException, ClassNotFoundException, IOException { Class.forName ("oracle.jdbc.OracleDriver"); Connection ARS; ARS =DriverManager.getConnection(ARS_URL, "whitney", "secret"); ARS.setAutoCommit(false); String floodProblem = DELETE FROM AirlineSchedule WHERE from = 'FAR'; String newflight = INSERT INTO AirlineSchedule VALUES ( 'DE', 'SAN', '8:00', '12:00', '909', 'A'); Statement schedule = ARS.createStatement (); schedule.executeUpdate (floodProblem); schedule.executeUpdate (newflight); ARS.commit(); ARS.close(); } }
The SQL statements contains variables (IN parameters) which are given values before statement is executed
Only makes sense to use if database and driver keeps statements open after they have been committed
IN parameters are indicated by a ?
Values are set by position
String flightOut = "SELECT * FROM AirlineSchedule WHERE from = ?";
import java.sql.*; import java.io.*; class JdbcTest { static String ARS_URL = "jdbc:oracle:@PutDatabaseNameHere"; public static void main (String args []) throws SQLException, ClassNotFoundException, IOException { Class.forName ("oracle.jdbc.OracleDriver"); Connection ARS; ARS =DriverManager.getConnection(ARS_URL, "whitney", "secret"); String flightOut = "SELECT * FROM AirlineSchedule WHERE from = ?"; PreparedStatement schedule; schedule = ARS.preparedStatement (flightOut); schedule.setObject( 1, "SAN" ); ResultSet fromSanDiego = schedule.executeQuery (); schedule. clearParameters(); schedule.setObject( 1, "LAX" ); ResultSet fromLA = schedule.executeQuery (); } }
Some databases have stored procedures (a procedure of SQL statements)
CallableStatement allows a Java program to invoke a stored procedure in a database
The 113 methods in DatabaseMetaData gives you more
information than you thought possible