3104Chapter4_PPT

Embed Size (px)

Citation preview

  • 8/12/2019 3104Chapter4_PPT

    1/52

    1

    AACS 3104

    Chapter 4

    Java Database Programming

  • 8/12/2019 3104Chapter4_PPT

    2/52

    2

    Objectives

    To become familiar with the JDBC API(1.0).

    To learn how to load a driver, connectto adatabase, execute statements, and process resultsetsusing JDBC (2.0).

    To use the prepared statementsto executeprecompiled SQL statements(3.0).

    To process updateableand scrollableresult sets.

    (4.0)

  • 8/12/2019 3104Chapter4_PPT

    3/52

    3

    1.0 The Design and use of JBDC

    The Java API(Application Programming Interface) for

    developing Java Database applications is called JDBC.

    JDBC provides Java programmers with a uniform interfacefor accessingand manipulatinga wide range of relationaldatabases.

    Using the JDBC API, applications written in Javaprogramming language can execute SQL statements,

    retrieve results,

    present data in a user friendly interface, and propagates changes back to the database.

  • 8/12/2019 3104Chapter4_PPT

    4/52

    4

    1.0 The Design and use of JBDC (Contd)

    The relationship between Java program, JDBC API, JDBC

    drivers, and relational database are shown below.

    Java Programs

    JDBC API

    MySQL JDBC

    Driver

    Microsoft

    Access

    Database

    JDBC-ODBC

    Bridge Driver

    Oracle JDBC

    Driver

    MySQL

    Database

    Oracle

    Database

    Microsoft ODBCDriver

    This chapterwill cover how

    to connect to

    MS Access

    Database Only

  • 8/12/2019 3104Chapter4_PPT

    5/52

    5

    1.0 The Design and use of JBDC (Contd)

    Java Programs

    JDBC API

    MySQL JDBC

    Driver

    MicrosoftAccess

    Database

    JDBC-ODBC

    Bridge Driver

    Oracle JDBC

    Driver

    MySQL

    Database

    Oracle

    Database

    Microsoft ODBC

    Driver

    JDBC API is a set of interfaces

    and classesused to write Java

    programs for accessing andmanipulating relational databases.

    JDBC drivers are database-

    specific and are normallyprovided by the database

    vendors.

  • 8/12/2019 3104Chapter4_PPT

    6/52

    6

    1.0 The Design and use of JBDC (Contd)

    Table below shows the Database driver for different databasevendor.

    Database Database Driver

    MySQL MySQL JDBC driver (can be downloaded online)

    Oracle Oracle JDBC drivers (can be downloaded online)

    MsAccess JDBC-ODBC driver ( included in JDK)

    ODBC is a technology developed by Microsoft for accessing

    databases on the Windows platform

    An ODBC driver is preinstalledon Windows.

    The JDBC-ODBC bridge driver allows a Java program to access

    any ODBC data source.

  • 8/12/2019 3104Chapter4_PPT

    7/527

    2.0 Connecting to and Querying a Database

    2.1 JDBC Appl ic at ion Programm ing Interface (API) Driver

    Connect ion

    Statements

    ResultSet

    2.2 Steps in con nect ing and querying a database

    Step 1: Loading Driver

    Step 2: Establ ishing Connect ion

    Step 3: Creat ing and Execut ing Statements

    Step 4: Processing ResultSet ob ject

    2.3 Example

  • 8/12/2019 3104Chapter4_PPT

    8/528

    2.1 JDBC Application Programming I nterface (API )

    The JDBC API consists of classes and interfaces

    for Establishingconnectionswith databases,

    Sending SQL statementsto databases,

    Processingthe resultsof the SQL statements

    and etc.

    Four (4) key interfaces are needed to develop anydatabase application using Java:

    1. Driver2. Connection

    3. Statements

    4. ResultSet

  • 8/12/2019 3104Chapter4_PPT

    9/529

    2.1 JDBC Application Programming I nterface (API )

    Driver

    Connection Connection

    Statement Statement Statement Statement

    ResultSet ResultSet ResultSet ResultSet

    Creating andexecutingstatements

    Establishing

    connections

    ProcessingResultSet

    Load Driver

    The relationship of the 4 interfaces is shown in Figure 4.2.

    Figure 4.2 Relationships betweenDriver, Connection, Statement

    andResultSet.

  • 8/12/2019 3104Chapter4_PPT

    10/5210

    2.2 Steps in connecting and querying a database

    The JDBC interfaces and classes are the building blocks in

    the development of Java database programs

    A typical Java program takes the following steps to access

    the database:

    Step 1:

    Loading driver

    Step 2:

    Establish connection

    Step 3:Create and Execute statement

    Step 4:

    Process resultset

  • 8/12/2019 3104Chapter4_PPT

    11/5211

    An appropriate driver must be loaded using the statement shown below

    before connecting a database.The Driver class for MS Access is sun.jdbc.odbc.JdbcOdbcDriver

    Statement to load a driver:

    Class.forName(");

    A driver is a class. For example:

    Database Driver Class Source

    Access sun.jdbc.odbc.JdbcOdbcDriver Already in JDK

    NOTE: The JDBC-ODBC driver for Access is bundled in JDK.

    Loading

    drivers

    Establishing

    connections

    Creating and

    executing

    Statements

    Processing

    ResultSet

    put in here

    2.2Steps in connecting and querying a database (Contd)

  • 8/12/2019 3104Chapter4_PPT

    12/5212

    A connection is like a cablethat links your program to a

    database.

    To connect to a database, use the static method

    getConnection(databaseURL) in the DriverManagerclass

    Connectionconnection=

    DriverManager.getConnection(databaseURL);

    Database URL PatternAccess jdbc:odbc:dataSource

    See Appendix A in Lecture Note

    for creating an ODBC data source

    Loading

    drivers

    Establishing

    connections

    Creating and

    executing

    Statements

    Processing

    ResultSet

    put in here

    2.2Steps in connecting and querying a database (Contd)

  • 8/12/2019 3104Chapter4_PPT

    13/52

    13

    Loading drivers

    Establishingconnections

    Creating and

    executing

    statements

    Processing

    ResultSet

    Example:

    Suppose a data source named CustomerDBhas beencreated for a MS Accessdatabase

    we create the connection as follows:

    ConnectionconCustomer=

    DriverManager.getConnection("jdbc:odbc:CustomerDB");

    2.2Steps in connecting and querying a database (Contd)

  • 8/12/2019 3104Chapter4_PPT

    14/52

    14

    An object of Statementcan be viewed as a cartthat

    deliversSQLstatements for execution by the database and

    brings backthe resultback to the program.

    Statementstatement= connection.createStatement( );

    Where

    connectionis Connectionobject created.

    2.2Steps in connecting and querying a database (Contd)

    Loading drivers

    Establishingconnections

    Creating and

    executing

    statements

    Processing

    ResultSet

  • 8/12/2019 3104Chapter4_PPT

    15/52

    15

    Once a Statement object is created, we can use it to

    execute executing SQL statements.

    2.2Steps in connecting and querying a database (Contd)

    Loading drivers

    Establishingconnections

    Creating and

    executing

    statements

    Processing

    ResultSet

    SQL Types Statement method used

    INSERT, UPDATE

    and DELETE

    executeUpdate( Stringsql)

    SELECT query

    NOTE:

    query result is stored

    in ResultSetobject

    executeQuery(Stringsql) : ResultSet

  • 8/12/2019 3104Chapter4_PPT

    16/52

    16

    Lets assume that we have a table called Customerswith

    the following fields:Customers(cust_ID, cust_Name, cust_Address)

    To INSERT new customer:

    StatementstmtInsert= conCustomer.createStatement();

    stmtInsert.executeUpdate(INSERT INTO Customers

    VALUES(C100, Adam, KL));

    2.2Steps in connecting and querying a database (Contd)

    Loading drivers

    Establishingconnections

    Creating and

    executing

    statements

    Processing

    ResultSet

    Use executeUpdate() method because we want to

    INSERT record

  • 8/12/2019 3104Chapter4_PPT

    17/52

    17

    2.2Steps in connecting and querying a database (Contd)

    Loading drivers

    Establishingconnections

    Creating and

    executing

    statements

    Processing

    ResultSet

    Lets assume that we have a table called Customerswith

    the following fields:

    Customers(cust_ID, cust_Name, cust_Address)

    To query (SELECT)customer record

    StatementstmtSelect= conCustomer.createStatement();

    ResultSetrsCustomer; // declare ResultSet object to store query result

    // select all customer recordrsCustomer= stmtSelect.executeQuery(SELECT * FROM

    Customers);

    //then we can process the result in rsCustomer later, see step 4

  • 8/12/2019 3104Chapter4_PPT

    18/52

    18

    The ResultSetmaintains a table whose current row

    can be retrieved.The initialrowpositionis null.

    A defaultResultSetobject is NOTupdatableand has a

    cursor that moves forward ONLY.

    2.2Steps in connecting and querying a database (Contd)

    Loading drivers

    Establishingconnections

    Creating and

    executing

    statements

    Processing

    ResultSet

  • 8/12/2019 3104Chapter4_PPT

    19/52

    19

    Some useful methods in ResultSet:

    2.2Steps in connecting and querying a database (Contd)

    Methods Description

    next() Moves the cursor to the

    next row.

    Returns false if there are

    no more rows in theResultSet object

    getXxx( int ColumnIndex) : Xxx Retrieves the value at the

    specified column index as

    Xxxtype value

    getXxx( String columnName) : Xxx Retrieves the value at the

    specified column index as

    Xxxtype value

    Column index in ResultSet starts from 1 (ONE)

    Loading drivers

    Establishingconnections

    Creating and

    executing

    statements

    Processing

    ResultSet

  • 8/12/2019 3104Chapter4_PPT

    20/52

    20

    Example:

    rsCustomer.next() // move cursor to next row

    // get String value from 1stcolumnin result set and store in a

    // String variable

    String customerID = rsCustomer.getString(1);

    OR

    // get String value from Column nameCust_Namein result set

    // and store in a String variable

    String customerName = rsCustomer.getString(Cust_Name);

    2.2Steps in connecting and querying a database (Contd)

    Loading drivers

    Establishingconnections

    Creating and

    executing

    statements

    Processing

    ResultSet

  • 8/12/2019 3104Chapter4_PPT

    21/52

    21

    Lets assume that we have a table called Customerswith the

    following fields:

    Customers(cust_ID, cust_Name, cust_Address)

    To query (SELECT)customer record

    StatementstmtSelect= conCustomer.createStatement();

    ResultSetrsCustomer; // declare ResultSet object to store query result

    // select all customer names

    rsCustomer= stmtSelect.executeQuery(SELECT cust_Name FROM

    Customers);

    // loop through the resultset and display the customer names

    while( rsCustomer.next() )

    { // display customer name on the console

    System.out.println(name: + rsCustomer.getString(1));

    }

    2.2Steps in connecting and querying a database (Contd)

    Loading drivers

    Establishingconnections

    Creating and

    executing

    statements

    Processing

    ResultSet

  • 8/12/2019 3104Chapter4_PPT

    22/52

    22

    2.3 Example: connecting and querying MS Access Database

    Example 1:

    The program in Listing 4.1 connects to an ODBCdata sou rcenamed CustomerDB and makes query

    to all customers record.

    (See Appendix A [ Page 22in lecture note ] on how to

    create ODBC data source)

    It then displays all the customer names in the

    console.

    The Customerstable in CustomerDB is as follows:

    Customers( Cust_ID, Cust_Name, Cust_Address )

    Run SimpleJDBC view SimpleJDBC codeHOW TO create

    ODBC data source

    http://localhost/var/www/apps/conversion/tmp/scratch_4/HowToCreateODBCDataSource.pdfhttp://localhost/var/www/apps/conversion/tmp/scratch_4/HowToCreateODBCDataSource.pdf
  • 8/12/2019 3104Chapter4_PPT

    23/52

  • 8/12/2019 3104Chapter4_PPT

    24/52

    24

    2.3 Example: connecting and querying MS Access Database

    Example 3:

    Retrieve data from Database and bind them to a Combo Box

    // in the constructor in GUI application

    Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);

    ConnectionconCustomer=

    DriverManager.getConnection(jdbc:odbc:CustomerDB);

    StatementstmtCustomer= conStudent.createStatement();

    ResultSetrsCustomer= stmtCustomer.executeQuery("SELECT Cust_ID FROM

    Customers");

    while( rsCustomer.next() ){ String custID = rsCustomer.getString(1); // get Cust_ID value

    // need to convert String value to Object ,

    // this is because the addItem(Object o) method only accept Object type value

    jcboCustomerID.addItem( (Object)custID);

    }

  • 8/12/2019 3104Chapter4_PPT

    25/52

    25

    3.0 PreparedStatement

    The Statementinterface is used to execute static

    (fixed) SQL statements that contains NO parameters

    In order words, you MUSTalready specifiedthe values

    in the condition in the WHEREclause.

    However, Java also provides the PreparedStatement,

    which extendingStatementand can be used toexecute a precompiledSQL statement with or without

    parameters.

  • 8/12/2019 3104Chapter4_PPT

    26/52

    26

    3.0 PreparedStatement (Contd)

    Since the SQL statements are precompiled,they are efficientfor repeated executions

  • 8/12/2019 3104Chapter4_PPT

    27/52

    27

    3.0 PreparedStatement (Contd)

    The PreparedStatementobject is created using the

    prepareStatement(String sql)method in the Connection

    interface.

    String sqlSelect = Insert Into Customer (Cust_ID, Cust_Name,

    Cust_Address) Values(?, ?, ?);

    PreparedStatementpstmt = connection.prepareStatement(sqlSelect);

    The INSERT statement has 3 question marks (?) asplaceholdersfor parametersrepresenting values for

    Cust_ID, Cust_Name, Cust_Address in a record of the

    Customer table.

  • 8/12/2019 3104Chapter4_PPT

    28/52

    28

    3.0 PreparedStatement (Contd)

    PreparedStatementinterface provides methods to setthe

    valuesof the parametersin the object of PreparedStatement. In general, the set methods have the following name and

    signature:

    setX( int parameterIndex, Xvalue);

    whereparameterIndexis the index of the parameter in the statement

    Xis the type of the parameterFor example:

    setString(2 , adam );

    // set the 2nd parameter value to a String value adam

  • 8/12/2019 3104Chapter4_PPT

    29/52

    29

    3.0 PreparedStatement (Contd)

    Lets see a more complete example:

    The following codes passthe parametersC007, Jeverson ,PJ to the placeholderfor Cust_ID, Cust_Name and

    Cust_Address in the PreparedStatementpstmt declared just now.

    String sqlSelect= Insert Into Customer (Cust_ID, Cust_Name,Cust_Address) Values(?, ?, ?);

    PreparedStatementpstmt=connection.prepareStatement(sqlSelect);

    pstmt.setString(1 , C007 );pstmt.setString(2 , Jeverson );Pstmt.setString(3 , PJ );

  • 8/12/2019 3104Chapter4_PPT

    30/52

    30

    3.0 PreparedStatement (Contd)

    After setting the parameters, you can execute the

    prepared statement by calling

    executeQuery()[ for SELECT statement], OR

    executeUpdate()[ for UPDATE, INSERT and DELETE

    statement ].

  • 8/12/2019 3104Chapter4_PPT

    31/52

    31

    3.0 PreparedStatement (Contd)

    Example 4: Insert Customer record using

    PreparedStatement object

    Sample output

    Run InsertCustomerPreparedStatement

    InsertCustomerPreparedStatement Code

  • 8/12/2019 3104Chapter4_PPT

    32/52

    32

    3.0 PreparedStatement (Contd)

    HOW DOES IT WORK?

    From line 812,

    the necessary JTextFieldsand JButtonsare declared.

    In line 15,

    a PreparedStatementobject called pstmtCustomeris declared.

    It is declared as data member so that its lifetimeand scope

    starts when the program starts and ends when the program

    ends.

  • 8/12/2019 3104Chapter4_PPT

    33/52

    33

    3.0 PreparedStatement (Contd)

    Then in the constructor, it does the following:

    1. call the initializedDB() method

    From line 4965, 1st load the driver, then establishthe

    connection.

    Then create a Stringobject to store the INSERT SQL statement.

    Then create the PreparedStatementobject pstmtCustomerobject by calling the prepareStatement()method from

    Connectionobject and pass in the SQL string value.

  • 8/12/2019 3104Chapter4_PPT

    34/52

    34

    3.0 PreparedStatement (Contd)

    Then in the constructor, it does the following:

    2. setup GUI components, add them to JFrame

    3. addActionListener for the 2 buttons, namely jbtAdd and

    jbtClear

    in addCustomer method for jbtAdd

    get textfieldvalue accordingly

    Call setString() method of PreparedStatementobject to set

    theparameter values.

    Call executeUpdate() method to update the INSERT

    statement to database.

  • 8/12/2019 3104Chapter4_PPT

    35/52

    35

    4.0 Scrollable and Updateable ResultSet

    The ResultSetused in the preceding examples are

    sequentially forward reading.

    Sequential forward reading means

    the resultset maintainsa cursorpointing to its

    current rowof data.

    Initiallythe cursor is positioned before the 1st row.

    The next() method movesthe cursorforward to the

    next row.

    There is to move backwardor update

    the resultset and have the changes automatically

    reflected in the database

    NO WAY

  • 8/12/2019 3104Chapter4_PPT

    36/52

    36

    4.0 Scrollable and Updateable ResultSet (Contd)

    With JDBC 2, you can scrollthe row both forwardand

    backwardand movethe cursor to a desired location.

    You can also insert, deleteor updatea row in a result

    set and have the changes automaticallyreflectedin

    the database.

  • 8/12/2019 3104Chapter4_PPT

    37/52

    37

    4.0 Scrollable and Updateable ResultSet (Contd)

    To obtain scrollable and updateable result set, you must

    first create a statement with an appropriate typeandconcurrency mode.

    For a static Statement object, use

    Statementstmt = connection.createStatement( int resultType,int resultsetConcurrency);

    For a preparedStatement object, use

    PreparedStatementpstmt = connection.prepareStatement(

    String sql, int resultType, int resultsetConcurrency);

  • 8/12/2019 3104Chapter4_PPT

    38/52

  • 8/12/2019 3104Chapter4_PPT

    39/52

    39

    4.0 Scrollable and Updateable ResultSet (Contd)

    The value of resultsetConcurrencycound be:

    resultsetConcurrency Possible values:

    ResultSet.CONCUR_READ_ONLY

    The result set CAN NOTbe used to update

    the database

    ResultSet.CONCUR_UPDATABLE

    The result set can be used to updatethe

    database

    Note:

    UPDATABLE,

    not

    UPDATEABLE

  • 8/12/2019 3104Chapter4_PPT

    40/52

    40

    4.0 Scrollable and Updateable ResultSet (Contd)

    For example, if you want the result set to

    be scrollableand updateable, you can

    create a statement as follows:

    Statementstmt = connection.createStatement(

    ResultSet.TYPE_SCROLL_SENSITIVE,

    ResultSet.CONCUR_UPDATABLE);

    Reminder Again:

    UPDATABLE, not

    UPDATEABLE

  • 8/12/2019 3104Chapter4_PPT

    41/52

    41

    4.0 Scrollable and Updateable ResultSet (Contd)

    After that, you can used the executeQuery() method

    of the Statementobject to execute an SQL query

    that returns a result set, as follows:

    ResultSetresultset = stmt.executeQuery(String sqlQuery);

  • 8/12/2019 3104Chapter4_PPT

    42/52

    42

    4.0 Scrollable and Updateable ResultSet (Contd)

    Then, you can use the various useful method in

    ResultSet interface to scroll(move ) around result

    or make changesto the resultset and have the

    changes automatically reflected in the database

    You can:

    1. Scroll or move cursor around resultset

    2. Retrieve value of a specified field in the current row

    3. Delete the current row

    4. Insert a new row ( means new record )5. Update a particular row

  • 8/12/2019 3104Chapter4_PPT

    43/52

    43

    4.0 Scrollable and Updateable ResultSet (Contd)

    TO Scrollor movecursor around result set

    Methods Description

    first() Move cursor to the 1strow

    next() Move cursor to the nextrow

    previous() Move cursor to the previousrow

    last() Move cursor to the lastrow

    absolute(int row) Move cursor to the specifiedrow

    Methods in ResultSet:

  • 8/12/2019 3104Chapter4_PPT

    44/52

    44

    4.0 Scrollable and Updateable ResultSet (Contd)

    TO Retrieve value of a specified field in the current row:

    1. getXxx( int columnIndex) : Xxx

    Retrieve the Xxx type value of a field specified by

    columnIndex. [ field index starts from 1 ]

    2. getXxx( String columnName) : Xxx

    Retrieve the Xxx type value of a field specified by

    columnName.

    [ same as field name in the database ]

    The type Xxxcould be String, int, doubleand etc..

  • 8/12/2019 3104Chapter4_PPT

    45/52

    45

    4.0 Scrollable and Updateable ResultSet (Contd)

    TO deletethe current row in the result set

    delete() Delete the current row in the result set,

    changeswill automatically reflectedin

    the database

  • 8/12/2019 3104Chapter4_PPT

    46/52

    46

    4.0 Scrollable and Updateable ResultSet (Contd)

    TO insert a new row in a resultset:

    3 Steps to insert a row:

    1. Call the moveToInsertRow() to movethe cursorto a

    special rowthat servesas a staging areafor building a row

    to be inserted.

    2. Then, update the columns using the

    updateXxx (int columnIndex, Xxxvalue) method or

    updateXxx( String columnName, Xxxvalue) method.

    NOTE: Xxx= type of the value, for example: String, int,

    double, and etc.

    3. Finally, insert the row using the insertRow() method.

  • 8/12/2019 3104Chapter4_PPT

    47/52

    47

    4.0 Scrollable and Updateable ResultSet (Contd)

    For example, the following code insert a new row

    with the new values:

    // 1st, move cursor to the insert row ( MUST DO SO)

    rsCustomer.moveToInsertRow();

    // 2nd, update Cust_ID, Cust_Name & Cust_Address

    rsCustomer.updateString(Cust_ID, C009);

    rsCustomer.updateString(Cust_Name, Julia);

    rsCustomer.updateString(Cust_Address, PJ);

    // 3rd, just call the insertRow() method to insert new row

    rsCustomer.insertRow();

  • 8/12/2019 3104Chapter4_PPT

    48/52

    48

    4.0 Scrollable and Updateable ResultSet (Contd)

    TO update a row in the result set

    3 Steps to update a row

    1. Move the cursor to desire row. You can use the

    absolute(introw) method.

    2. call the updateXxx() method to write new value

    to the field at the current row

    3. finally, call the updateRow() method to update

    row in the data source

  • 8/12/2019 3104Chapter4_PPT

    49/52

    49

    4.0 Scrollable and Updateable ResultSet (Contd)

    For example, the code below updates the address of the

    3rd row to Taman TBR

    // move cursor to the 3rd row

    rsCustomer.absolute(3);

    // updates the columns

    rsCustomer.updateString(Cust_Address, Taman

    TBR);

    // updates the row in the data source

    rsCustomer.updateRow();

  • 8/12/2019 3104Chapter4_PPT

    50/52

    50

    4.0 Scrollable and Updateable ResultSet (Contd)

    Other useful method in the ResultSet interface:

    cancelRowUpdates()

    Cancels the updates made to a row

    close()

    Closes the result set and releases its resources

    isFirst() : boolean

    To check whether the cursor is at the 1st row in the

    result setisLast() : boolean

    To check whether the cursor is at the last row in the

    result set

  • 8/12/2019 3104Chapter4_PPT

    51/52

    51

    4.0 Scrollable and Updateable ResultSet (Contd)

    Other useful method in the ResultSet interface:

    getRow(): int

    Return the current row number.

    The 1st row is 1, 2 for 2nd row and so on.

  • 8/12/2019 3104Chapter4_PPT

    52/52

    4.0 Scrollable and Updateable ResultSet (Contd)

    Example 5:

    Using Scrollable and Updateable Result Set

    The program in Listing 4.4 below demonstrates

    using scrollable and updateable result set to scrollcustomer record and insert new customer record.

    Run ViewCustomer ViewCustomer Code