Connecting toConnecting to Oracle using Oracle using JavaJava
November 4, 2009November 4, 2009
David Goldschmidt, Ph.D.David Goldschmidt, Ph.D.
[email protected]@gmail.com
JDBC is a platform-independent Java JDBC is a platform-independent Java API for executing SQL statementsAPI for executing SQL statements
Use JDBC to:Use JDBC to: Connect to a databaseConnect to a database Send SQL statementsSend SQL statements Receive resultsReceive results
i.e. rows of datai.e. rows of data Add or update existing rows of dataAdd or update existing rows of data Call PL/SQL procedures, functions, etc.Call PL/SQL procedures, functions, etc.
JDBCJDBC
Javaprogram
database
JDBC
Before connecting to a database,Before connecting to a database,a a driver classdriver class must first be loaded into must first be loaded intothe Java Virtual Machine (or JVM)the Java Virtual Machine (or JVM)
A A driverdriver is simply a class in Java is simply a class in Java MySQL:MySQL: "com.mysql.jdbc.Driver""com.mysql.jdbc.Driver" Oracle:Oracle: "oracle.jdbc.driver.OracleDriver""oracle.jdbc.driver.OracleDriver"
Oracle driver is located within the Oracle driver is located within the ojdbc14.jarojdbc14.jar JAR file of the Oracle JAR file of the Oracle distributiondistribution
JDBC DriversJDBC Drivers
Sun defines four categories of JDBC drivers:Sun defines four categories of JDBC drivers:1.1. JDBC bridge driverJDBC bridge driver – uses native code to connect a – uses native code to connect a
Java client to a third-party API (e.g. JDBC-ODBC)Java client to a third-party API (e.g. JDBC-ODBC)
2.2. Native API (part Java driver)Native API (part Java driver) – wraps native code – wraps native code with Java classes (e.g. with Java classes (e.g. Oracle Call InterfaceOracle Call Interface ( (OCIOCI ) ) driver)driver)
3.3. Network protocol (pure Java driver)Network protocol (pure Java driver) – Java classes – Java classes communicate via a network protocol to a middle-communicate via a network protocol to a middle-tier server, which communicates with the tier server, which communicates with the databasedatabase
4.4. Native protocol (pure Java driver)Native protocol (pure Java driver) – Java classes – Java classes communicate directly with the database (e.g. communicate directly with the database (e.g. ThinThin))
JDBC DriversJDBC Drivers
JDBC DriversJDBC Drivers
Oracle RDBMS
Oracle Listener
Oracle CallInterface
(OCI)
JDBC OCIdriver
JDBC-ODBCdriver
ODBCdriver
JDBC Thindriver
Connect to a database using its Connect to a database using its connect stringconnect string(i.e. its (i.e. its Connection URLConnection URL):): Access:Access: "jdbc:odbc:"jdbc:odbc:dataSourcedataSource"" MySQL:MySQL: "jdbc:mysql://"jdbc:mysql://hostnamehostname//dbnamedbname"" Oracle:Oracle:"jdbc:oracle:thin:@"jdbc:oracle:thin:@hostnamehostname::portport#:#:SIDSID""
Use a Use a ConnectionConnection object: object: Connection connection =Connection connection =
DriverManager.getConnection( dbConnectURL ); DriverManager.getConnection( dbConnectURL );
JDBC Connection StringsJDBC Connection Strings
JDBC InterfacesJDBC Interfaces
Driver
Connection Connection
StatementStatement Statement Statement
ResultSet ResultSetResultSetResultSet
Using JDBCUsing JDBC
Statement createStatement()Statement createStatement() Prepare a query without parametersPrepare a query without parameters Result set is read-only and Result set is read-only and forward-forward-
onlyonly For repeated queries, gain For repeated queries, gain
performance speedup by using performance speedup by using prepareStatement()prepareStatement() instead instead
Building StatementsBuilding Statements
PreparedStatementPreparedStatement
prepareStatement( String sql ) prepareStatement( String sql ) Prepare a parameterized queryPrepare a parameterized query Result set is read-only and Result set is read-only and
forward-onlyforward-only
Building StatementsBuilding Statements
CallableStatementCallableStatement
prepareCall( String sql ) prepareCall( String sql ) Prepare a call to a stored procedurePrepare a call to a stored procedure
Register any Register any OUTOUT (or (or ININ OUTOUT) parameters) parameters Set any Set any ININ (or (or ININ OUTOUT) parameters) parameters
Results are read-only and Results are read-only and forward-forward-onlyonly
Building StatementsBuilding Statements
boolean execute( String sql )boolean execute( String sql ) Use this method to execute DDL Use this method to execute DDL
statements and stored proceduresstatements and stored procedures Return value indicates whetherReturn value indicates whether
a a ResultSetResultSet object is available object is available
Processing StatementsProcessing Statements
might be emptyif zero rows!
ResultSet executeQuery( String sql )ResultSet executeQuery( String sql ) Use this method to execute DDL Use this method to execute DDL
statements you expect to receive statements you expect to receive results fromresults from
i.e. Use for your i.e. Use for your SELECTSELECT statements statements
Processing StatementsProcessing Statements
int executeUpdate( String sql )int executeUpdate( String sql ) Use this method to execute Use this method to execute INSERTINSERT, , UPDATEUPDATE, and , and DELETEDELETE statements statements
Return value is the number of Return value is the number of rows affectedrows affected
Processing StatementsProcessing Statements
Default Default ResultSetResultSet behavior behavioris read-only and is read-only and forward-onlyforward-only Change default using Change default using resultSetTyperesultSetType
and and resultSetConcurrencyresultSetConcurrency parametersparameters
For For resultSetTyperesultSetType:: TYPE_FORWARD_ONLYTYPE_FORWARD_ONLY TYPE_SCROLL_INSENSITIVETYPE_SCROLL_INSENSITIVE TYPE_SCROLL_SENSITIVETYPE_SCROLL_SENSITIVE
Processing ResultsProcessing Results
ResultSet
ResultSet
sensitivity refers to whetherdatabase changes made while
the ResultSet object is openare visible
scrolling uses a client-side memory cache
For For resultSetConcurrencyresultSetConcurrency:: CONCUR_READ_ONLYCONCUR_READ_ONLY CONCUR_UPDATABLECONCUR_UPDATABLE
To implement updateability, all To implement updateability, all queries request the queries request the ROWIDROWID for each for each rowrow
Processing ResultsProcessing Results
ResultSet
ROWID is a proprietary SQL data typethat uniquely identifies each row ofthe database
A scroll-sensitiveA scroll-sensitive ResultSetResultSet must: must: Perform Perform SELECTSELECT against only one table against only one table Explicitly specify columns (i.e. not Explicitly specify columns (i.e. not SELECTSELECT **))
Not use an Not use an ORDERORDER BYBY clause clause
An updateable An updateable ResultSetResultSet must must alsoalso:: Include all nonnullable columns (for Include all nonnullable columns (for INSERTINSERT))
Sensitivity and Sensitivity and UpdateabilityUpdateability
Improve performance by combining Improve performance by combining multiple SQL statements into a multiple SQL statements into a batchbatch Disable auto-commitDisable auto-commit Oracle supports Oracle supports PreparedStatementPreparedStatement batching batching
onlyonly Call Call addBatch()addBatch() instead of instead of executeUpdate()executeUpdate()
Repeat!Repeat! Then call Then call executeBatch()executeBatch() and and commit()commit() Tune frequency of commitsTune frequency of commits Use Use clearBatch()clearBatch() to cancel your batch to cancel your batch
BatchingBatching