Anda di halaman 1dari 27

Lecture 1 - Advanced Java Programming

Database Connectivity

JDBC
The JDBC API Components

JDBC
The Application Layer encompasses 3 interfaces that are implemented at the Driver Layer but used at the application layer. Recall: An interface allows a general name to indicate a specific object. The general name defines methods that must be implemented by the specific object classes. The 3 interfaces used at the Application Layer are Connection, Statement and Resultset. A connection object is obtained from the driver implementation through DriverManager.getConnection() method call Once a connection is resturned, a statement object to issue against the database can be created.

Connecting to the database


The results of a Statement is a Resultset object which contains the results of the particular statement (if any). The Connection interface represents a session with the database connection provided by the Driver. Typical db connections include the ability to control changes made to the data stored through transactions. A Transaction is a set of operations that are completed in order.
o o

Connection connection = null; Statement statement = null;

Codes to create Connection object


import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DBConnection{ static final String JDBC_DRIVER="... "; static final String DATABASE_URL="... "; public static void main(String args[]) { Connection connection =null; try{ Class.forName(JDBC_DRIVER); connection = DriverManager.getConnection(DATABASE_URL,"","");

Codes to create Connection object


}//end of try catch(SQLException sqlException){ sqlException.printStackTrace(); System.exit(1);} catch(ClassNotFoundException classNotFound){ classNotFound.printStackTrace(); System.exit(1);} finally{ try{ connection.close(); } catch(Exception exception){ exception.printStackTrace(); System.exit(1);} }}}

Explanation of connection codes


The program must load the db driver before connecting to the database. The static method forName of class Class is used to load the class for the database driver. The above throws a checked exception of type java.lang.ClassNotFoundException if the class Loader cannot locate the driver class. The program initialises connection with the result of a call to static method getConnection of class DriverManager which attempts to connect to the db driver. If the drivermanager cannot connect to the database, method getconnection throws an sqlexception (package java.sql).

The exception thrown


SQLException - if a database access error occurs, this method is called on a closed connection or the given parameters are not ResultSet constants indicating type and concurrency ClassNotFoundException Thrown when an application tries to load in a class through its string name using: The forName method in class Class. The findSystemClass method in class ClassLoader . The loadClass method in class ClassLoader. but no definition for the class with the specified name could be found.

The Finally block


Programs that contain certain types of resources must return them to the system explicitly to avoid resource leaks. For example, Files, database connections and network connections that have not been properly closed may not be available for use in other programs. The finally block consists of the finally keyword followed by code enclosed in curly brackets. Java guarantees that the finally block will execute whether or not an exception is thrown in the corresponding try block or any corresponding catch blocks. The finally block executes if a try block exits by using a return, break or continue statement.

Popular JDBC driver names and db names


RDBMS JDBC driver name
MySQL com.mysql.jdbc.driver

Database URL format


jdbc:mysql://hostname/databaseName jdbc:oracle:thin:@hostname:port Number:datebaseName jdbc:db2:hostname: portNumber/databaseName jdbc:odbc:Driver;DBQ

Oracle

oracle.jdbc.driver.OracleDriver

DB2

COM.ibm.db2.jdbc.net.DB2Driver

Access

sun.jdbc.odbc.JdbcOdbcDriver

The Statement interface


The primary use of the Connection interface is to create a Statement. Statement stmt; stmt = connection.createStatement(); The statement can be used to send SQL statements that return a single resultset in a Resultset object reference, or a count of the number of records affected by the statement. Statements that must be called a number of times with slight variations may be executed more efficiently using a PreparedStatement. PreparedStatement prepareStatement(String sql) returns a new PreparedStatement object. PreparedStatement objects are precompiled SQL statements.

The Statement interface


The Connection interface is also used to create CallableStatement whose primary purpose is to execute stored procedures. CallableStatement prepareCall(String sql) returns a new CallableStatement object. CallableStatement objects are SQL stored procedure call statements. The Statement class has three methods for executing statements: executeQuery(), executeUpdate(), and execute(). Statements may or may not return a Resultset object, depending on the Statement method used.

The Statement interface executeUpdate()


For statements that create or modify tables, the method to use is executeUpdate. Note: Statements that create a table, alter a table, or drop a table are all examples of DDL (Data Definition Language) statements and are executed with the method executeUpdate. The executeUpdate() method is used to execute SQL statements that do not expect a result(except a row count status). int rowCount; rowCount = stmt.executeUpdate("DELETE FROM customer WHERE CustomerID = 'Test'");

The Statement interface executeQuery()


Statements that do return a single set of results can use the executeQuery() method. This method returns a single Resultset object. The object represents the row information returned as a result of the query: Resultset results; results = stmt.executeQuery(SELECT * FROM Stock);

The Statement interface - execute()


SQL Statements that execute Stored Procedures may return more than one set of results. The execute() method is a general-purpose method that can be used to return a single result set, a result count, or some combination of both. execute() executes an SQL statement that is written as String object.

Resultset
The Resultset interface defines methods for accessing tables of data generated by executing a Statement. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The Resultset column values may be accessed in any order; they are indexed and may be selected either by name or the number of the column (from 1 to n). Resultset resultSet = stmt.executeQuery("SELECT * FROM Authors");

Recall(OOSD): Resultset Methods


When a ResultSet object is first created, the cursor is positioned before the first row. To move the cursor, the following methods can be used: The next() method is used to successively step through the rows of the tabular results. previous() - moves the cursor backwards one row. Returns true if the cursor is now positioned on a row and false if the cursor is positioned before the first row. first() - moves the cursor to the first row in the ResultSet object. Returns true if the cursor is now positioned on the first row and false if the ResultSet object does not contain any rows.

Recall(OOSD): Resultset Methods


last() - moves the cursor to the last row in the ResultSet object. Returns true if the cursor is now positioned on the last row and false if the ResultSet object does not contain any rows. getString(), getDouble(), getInt() and other methods - retrieves the data from the resultset, retrieves the data from the current row in the resulting data table.

ResultsetMetaData
ResultSetMetaData Interface holds information on the types and properties of the columns in a ResultSet. It is constructed from the Connection object.

The complete codes


See DisplayAuthors.java codes

The CreateStatement method


Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException Creates a Statement object that will generate ResultSet objects with the given type and concurrency. This method is the same as the createStatement method above, but it allows the default result set type and concurrency to be overridden. Returns:a new Statement object that will generate ResultSet objects with the given type and concurrency Parameters: resultSetType - a result set type; one of ResultSet.TYPE_FORWARD_ONLY, Specifies that a Resultset's cursor can move only in the forward direction(ie from first row to last row in the Resultset)

The CreateStatement method


ResultSet.TYPE_SCROLL_INSENSITIVE, Specifies that a Resultset's cursor can scroll in either directions and that changes made to the resultset during the resultset processing are not reflected in the Resultset unless the program queries the database again ResultSet.TYPE_SCROLL_SENSITIVE Specifies that a resultset's cursor can scroll in either directions and that changes made to the Resultset during resultset processing are reflected immediately in the resultset

The CreateStatement method


resultSetConcurrency - a concurrency type; one of ResultSet.CONCUR_READ_ONLY Specifies that a resultset cannot be updated (i.e. changes made to the resultset contents cannot be reflected in the database with the resultset's update method) ResultSet.CONCUR_UPDATABLE Specifies that a Resultset can be updated(i.e. changes made to the resultset contents can be reflected in the database with the resultset update method) Example: statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );

PreparedStatement
If an SQL statement needs to be executed many times but with different values, a prepared statement can be used to improve performance. For example, if on a website users look up product information with a product id using the same query each time, a prepared statement should be used. A prepared statement is a precompiled SQL statement and its use saves the database from repeatedly having to compile the SQL statement each time it is executed. A query in a prepared statement contains placeholders (represented by the '?' character) instead of explicit values. The values for these placeholders can be set and then the prepared statement is executed.

Codes for inserting a row using PreparedStatement


try { // Prepare a statement to insert a record String sql="INSERT INTO my_table (col_string) VALUES(?)"; PreparedStatement pstmt=connection.prepareStatement(sql); // Insert 10 rows for (int i=0; i<10; i++) { // Set the value pstmt.setString(1, "row "+i); // Insert the row pstmt.executeUpdate(); } } catch (SQLException e) { }

Codes for inserting a row using PreparedStatement


The values to be used in place of the question mark placeholders (if there are any) need to be supplied before a PreparedStatement object is executed. This is done by calling one of the setXXX methods defined in the PreparedStatement class. If the value to substitute for a question mark is a Java int, the method setInt is called. If the value is a Java String, the method setString is called, and so on. In general, there is a setXXX method for each primitive type declared in the Java programming language.

Anda mungkin juga menyukai