+ All Categories
Home > Documents > Lecture 1 Advanced Java Programming

Lecture 1 Advanced Java Programming

Date post: 07-Apr-2018
Category:
Upload: aali-yah
View: 232 times
Download: 0 times
Share this document with a friend

of 27

Transcript
  • 8/4/2019 Lecture 1 Advanced Java Programming

    1/27

    Lecture 1 - Advanced Java

    ProgrammingDatabase Connectivity

  • 8/4/2019 Lecture 1 Advanced Java Programming

    2/27

    JDBC

    The JDBC API Components

  • 8/4/2019 Lecture 1 Advanced Java Programming

    3/27

    JDBC

    The Application Layer encompasses 3 interfaces that areimplemented 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 areConnection, 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.

  • 8/4/2019 Lecture 1 Advanced Java Programming

    4/27

    Connecting to the database

    The results of a Statement is a Resultset object whichcontains the results of the particular statement (if any).

    The Connection interface represents a session with thedatabase connection provided by the Driver. Typical dbconnections include the ability to control changes made to

    the data stored through transactions. A Transaction is a set of operations that are completed inorder.

    o Connection connection = null;o Statement statement = null;

  • 8/4/2019 Lecture 1 Advanced Java Programming

    5/27

    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,"","");

  • 8/4/2019 Lecture 1 Advanced Java Programming

    6/27

    Codes to create Connection object

    }//end of trycatch(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);}

    }}}

  • 8/4/2019 Lecture 1 Advanced Java Programming

    7/27

    Explanation of connection codes

    The program must load the db driver before connecting tothe database.

    The static method forName of class Class is used to loadthe class for the database driver.

    The above throws a checked exception of type

    java.lang.ClassNotFoundException if the class Loadercannot 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).

  • 8/4/2019 Lecture 1 Advanced Java Programming

    8/27

    The exception thrown

    SQLException - if a database access error occurs, this methodis called on a closed connection or the given parameters are

    not ResultSet constants indicating type and concurrencyClassNotFoundException -

    Thrown when an application tries to load in a class through itsstring 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 befound.

  • 8/4/2019 Lecture 1 Advanced Java Programming

    9/27

    The Finally block

    Programs that contain certain types of resources mustreturn them to the system explicitly to avoid resource leaks.

    For example, Files, database connections and networkconnections that have not been properly closed may not beavailable for use in other programs.

    The finally block consists of the finallykeyword followed bycode 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.

  • 8/4/2019 Lecture 1 Advanced Java Programming

    10/27

    Popular JDBC driver names and db

    namesRDBMS JDBC driver name Database URL format

    MySQL com.mysql.jdbc.driver jdbc:mysql://hostname/database-Name

    Oracle oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:portNumber:datebaseName

    DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:

    portNumber/databaseName

    Access sun.jdbc.odbc.JdbcOdbcDriver jdbc:odbc:Driver;DBQ

  • 8/4/2019 Lecture 1 Advanced Java Programming

    11/27

    The Statement interface

    The primary use of the Connection interface is to create aStatement.

    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 acount 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 aPreparedStatement. PreparedStatement prepareStatement(String sql)

    returns a new PreparedStatement object.

    PreparedStatement objects are precompiled SQLstatements.

  • 8/4/2019 Lecture 1 Advanced Java Programming

    12/27

    The Statement interface

    The Connection interface is also used to createCallableStatement 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.

  • 8/4/2019 Lecture 1 Advanced Java Programming

    13/27

    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 atable are all examples of DDL (Data Definition Language)statements and are executed with the method

    executeUpdate. The executeUpdate() method is used to execute SQLstatements that do not expect a result(except a row countstatus).

    int rowCount;rowCount = stmt.executeUpdate("DELETE FROM customer

    WHERE CustomerID = 'Test'");

  • 8/4/2019 Lecture 1 Advanced Java Programming

    14/27

    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 informationreturned as a result of the query:

    Resultset results;results = stmt.executeQuery(SELECT * FROM Stock);

  • 8/4/2019 Lecture 1 Advanced Java Programming

    15/27

    The Statement interface - execute()

    SQL Statements that execute Stored Procedures may returnmore than one set of results.

    The execute() method is a general-purpose method that canbe used to return a single result set, a result count, or somecombination of both.

    execute() executes an SQL statement that is written asString object.

  • 8/4/2019 Lecture 1 Advanced Java Programming

    16/27

    Resultset

    The Resultset interface defines methods for accessingtables 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 thenumber of the column (from 1 to n).

    Resultset resultSet = stmt.executeQuery("SELECT * FROMAuthors");

  • 8/4/2019 Lecture 1 Advanced Java Programming

    17/27

    Recall(OOSD): Resultset Methods

    When a ResultSet object is first created, the cursor ispositionedbefore the first row. To move the cursor, the following methods

    can be used:The next() method is used to successively step through therows of the tabular results.

    previous() - moves the cursor backwards one row. Returns trueif the cursor is now positioned on a row and false if the cursor ispositioned 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 andfalse if the ResultSet object does not contain any rows.

  • 8/4/2019 Lecture 1 Advanced Java Programming

    18/27

    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 currentrow in the resulting data table.

  • 8/4/2019 Lecture 1 Advanced Java Programming

    19/27

    ResultsetMetaData

    ResultSetMetaData Interface holds information on thetypes and properties of the columns in a ResultSet. It is

    constructed from the Connection object.

  • 8/4/2019 Lecture 1 Advanced Java Programming

    20/27

    The complete codes

    See DisplayAuthors.java codes

  • 8/4/2019 Lecture 1 Advanced Java Programming

    21/27

    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 methodis the same as the createStatement method above, but itallows the default result set type and concurrency to beoverridden.

    Returns:a new Statement object that will generateResultSet objects with the given type and concurrency

    Parameters:

    resultSetType - a result set type; one ofResultSet.TYPE_FORWARD_ONLY,Specifies that a Resultset's cursor can move only in theforward direction(ie from first row to last row in the Resultset)

  • 8/4/2019 Lecture 1 Advanced Java Programming

    22/27

    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 theresultset processing are not reflected in the Resultset unlessthe program queries the database again

    ResultSet.TYPE_SCROLL_SENSITIVESpecifies that a resultset's cursor can scroll in either directionsand that changes made to the Resultset during resultset

    processing are reflected immediately in the resultset

    C

  • 8/4/2019 Lecture 1 Advanced Java Programming

    23/27

    The CreateStatement method

    resultSetConcurrency - a concurrency type; one ofResultSet.CONCUR_READ_ONLYSpecifies that a resultset cannot be updated (i.e. changes

    made to the resultset contents cannot be reflected in thedatabase with the resultset's update method)

    ResultSet.CONCUR_UPDATABLE

    Specifies that a Resultset can be updated(i.e. changes madeto the resultset contents can be reflected in the database withthe resultset update method)

    Example:statement = connection.createStatement(

    ResultSet.TYPE_SCROLL_INSENSITIVE,

    ResultSet.CONCUR_READ_ONLY );

    P dS

  • 8/4/2019 Lecture 1 Advanced Java Programming

    24/27

    PreparedStatement

    If an SQL statement needs to be executed many times butwith 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 andits use saves the database from repeatedly having tocompile 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.

    C d f i i i

  • 8/4/2019 Lecture 1 Advanced Java Programming

    25/27

    Codes for inserting a row using

    PreparedStatementtry {

    // Prepare a statement to insert a record

    String sql="INSERT INTO my_table (col_string) VALUES(?)";PreparedStatementpstmt=connection.prepareStatement(sql);

    // Insert 10 rowsfor (int i=0; i

  • 8/4/2019 Lecture 1 Advanced Java Programming

    26/27

    The values to be used in place of the question mark

    placeholders (if there are any) need to be suppliedbefore 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.

    Codes for inserting a row using

    PreparedStatement

  • 8/4/2019 Lecture 1 Advanced Java Programming

    27/27


Recommended