M12 - JDBC

download M12 - JDBC

of 31

Transcript of M12 - JDBC

  • 8/10/2019 M12 - JDBC

    1/31

    Module 12Core Java API: JDBC

    Java Course

  • 8/10/2019 M12 - JDBC

    2/31

    2

    Module Objectives

    At the end of this module, participants will beable to:

    Use JDBC technology and describe its features.

    Use Database drivers and describe their

    features.

    Establish a connection to a database using theConnectionobject.

    Create and execute SQL statements in Java and

    manipulate data resulting from executed SQL

    statements.

    Define the concept of Database Access Objects.

  • 8/10/2019 M12 - JDBC

    3/31

  • 8/10/2019 M12 - JDBC

    4/31

    4

    Database Drivers

    Database Drivers or JDBCDrivers are required to connect

    to different databases. The

    JDBC requires different drivers

    for each database.

    JDBC drivers provide theconnection to the database and

    implement the protocol

    necessary for sending queries

    and retrieving results.

    Application

    JDBC API

    JDBC Driver

    Database

  • 8/10/2019 M12 - JDBC

    5/31

    5

    Database Drivers (cont.)

    Type 1 JDBC-ODBC Bridge + ODBC Driver Type 2 Native API / Partly Java technology-enabled driver

    Type 3 Pure Java Driver for Database Middleware

    Type 4 Direct to Database Pure Java Driver

  • 8/10/2019 M12 - JDBC

    6/31

    6

    Retrieving a Connection Object

    A Connectionobject defines a connection or session with aspecific database.

    It is where SQL statements are executed and results are

    returned.

    Before a Connectionobject can be used, the

    java.sql.Connectionclass has to be imported first.

  • 8/10/2019 M12 - JDBC

    7/317

    Retrieving a Connection Object (cont.)

    A database driver can be loaded by using theClass.forName()method.

    Syntax : Class.forName(JDBCDriver_Name);

    Example : Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

    A Connectionobject has three (3) important parts:

    The URL or location of the data source

    The username

    The password

  • 8/10/2019 M12 - JDBC

    8/318

    Retrieving a Connection Object (cont.)

    A connection can be established by using thegetConnection()method.

    Creating a connection by using the URL, username and

    password as parameters.

    Connection myConnection = DriverManager.getConnection ( URL, username, password );

    Creating a connection by using the URL; In this case, the URL

    already includes the username and password.

    Connection myConnection = DriverManager.getConnection ( URL );

    ** Refer to the ConnectionSample.java sample code

  • 8/10/2019 M12 - JDBC

    9/31

  • 8/10/2019 M12 - JDBC

    10/3110

    Creating Query Statements (cont.)

    A Statementis created by using the following syntax:

    Syntax : Statement = .createStatement();

    Sample : Connection myConn = DriverManager.getConnection();

    Statement myStatement = myConn.createStatement();

    A Statementneeds to use a Connectionobject to identify

    which connection the statement will be associated with.

  • 8/10/2019 M12 - JDBC

    11/31

    11

    Creating Query Statements (cont.)

    A Statementcan be executed by using either theexecute(), executeQuery()and executeUpdate()

    methods.

    Syntax : .executeQuery(SQL Statement goes here);

    Sample : Connection myConn = DriverManager.getConnection();

    Statement myStatement = myConn.createStatement();

    myStatement.executeQuery(Select * from aTable);

    ** Refer to the StatementSample.java sample code

  • 8/10/2019 M12 - JDBC

    12/31

  • 8/10/2019 M12 - JDBC

    13/31

    13

    Basic SELECT Statement (cont.)

    To retrieve data from two or more tables, the column nameshould be appended by the table name.

    Syntax:.

    Example:

    SELECT patients.name, meds.name FROM patients, meds WHERE patients.med_id= meds.med_id;

    Aliasing is used to shorten the statement.

    Syntax:

    .

    Example:SELECT a.name, b.name FROM patients a, meds b WHERE a.med_id = b.med_id;

  • 8/10/2019 M12 - JDBC

    14/31

    14

    Basic INSERT Statement

    Use the INSERT statement to add data to a specific table:

    INSERT INTO

    [ ( ) ]

    VALUES ()

    table- the name of the table where data is to be inserted.

    column- the names of the columns in the table to be populated.

    value - the corresponding values to be inserted for each column

    specified. Note: column is optional. Optional is represented by [ ]

    INSERT INTO userVALUES (Luis, Chua)

    INSERT INTO user(firstname, lastname) VALUES (Luis, Chua)

  • 8/10/2019 M12 - JDBC

    15/31

  • 8/10/2019 M12 - JDBC

    16/31

    16

    Basic DELETE Statement

    Use the DELETE statement to delete rows in a specific table:

    DELETE FROM

    [WHERE ] ;

    table - the name of the table.

    condition - identifies the rows to be deleted, which contains

    expressions, constraints, sub-queries, and comparison

    operators.

    DELETE FROM user WHERE firstname = Manny;

  • 8/10/2019 M12 - JDBC

    17/31

    17

    Creating Query Statements

    After a Statementhas been executed, it returns different kindsof data depending on the type of execute used.

    execute()returns a booleanvalue and is used to execute

    SQL statements written as a Stringobject.

    executeUpdate()returns an intvalue pertaining to the

    number of rows affected and is used to execute DDL SQLstatements.

    executeQuery()returns a ResultSetobject and is used to

    execute SELECT SQL statements.

  • 8/10/2019 M12 - JDBC

    18/31

    18

    Transactions

    Transaction management is vital for operations that modify orupdate the records in the database.

    Transaction management allows the application to confirm the

    execution of a group of SQL statements by committing the

    changes.

    Should an exception occur, the transaction can be rolled-backto undo the changes that were made.

  • 8/10/2019 M12 - JDBC

    19/31

    19

    Transactions (cont.)

    Setting the Connection.autocommit() field of the Connectionobject to false will prevent the statements from being committed

    until an explicit Connection.commit() is executed by the

    application.

    The Connection.rollback() method can be executed should an

    event occur requiring the changes made so far to be undone.

  • 8/10/2019 M12 - JDBC

    20/31

    20

    Using PreparedStatement

    PreparedStatementis a Java object, which represents aprecompiled SQL statement.

    PreparedStatementis usually used for SQL statements that

    take parameters, although it can also execute SQL statements

    that have no parameters.

    Before a Statement object can be used, thejava.sql.PreparedStatementclass has to be imported

    first.

  • 8/10/2019 M12 - JDBC

    21/31

    21

    Using PreparedStatement (cont.)

    A PreparedStatementis useful when an SQL statement hasto be executed multiple times.

    A PreparedStatementis precompiled, hence it is immediately

    executed by the DBMS, unlike Statement,which has to be

    compiled first.

    Syntax :

    PreparedStatement = .prepareStatement(");

    Example :Connection myConn = DriverManager.getConnection();

    PreparedStatement pStmt = myConn.prepareStatement(Select * from Dogs Where

    breed = ?);

  • 8/10/2019 M12 - JDBC

    22/31

    22

    Using PreparedStatement (cont.)

    The question mark (?) serves as a wildcard or parameter andcan be replaced with a value.

    The wildcard can be replaced by using the appropriate methodsfor a particular data type, including but not limited to:

    setString() setInt()

    setDouble()

    setDate()

    ** Refer to the PreparedStatementSample.java sample code

  • 8/10/2019 M12 - JDBC

    23/31

    23

    Using PreparedStatement (cont.)

    The PreparedStatementobject also has the differentexecution commands as the Statementobject, yielding similar

    results.

  • 8/10/2019 M12 - JDBC

    24/31

    24

    Questions and Comments

  • 8/10/2019 M12 - JDBC

    25/31

    25

    Setting up the Database

    1. MySQL 5.0 is an Accenture approved OSS. Please read the License

    Agreement located in the Appendix section of this module.

    2. Install MySQL 5. Refer to MySQL 5 Installation and Configuration

    Guide.doc. It will ask you create the root password. Type abcd1234.

    3. Install MySQL GUI Tools. Refer to MySQL GUI Tools Installation

    Guide.doc.

    4. Once installed, open Program Files -> MySQL -> MySQL Administrator.

    This will launch the MySQL Authentication UI as shown below.

  • 8/10/2019 M12 - JDBC

    26/31

    26

    Setting up the Database (cont.)

    5. Type in the root password entered during installation as the password then

    click OK. Once verified, the MySQL Administrator UI will be displayed.

    6. In the left pane of the UI, click the Restore option. This will display the

    Restore page.

    7. Click the Open Backup File button found at the lower right portion of the UI.

  • 8/10/2019 M12 - JDBC

    27/31

    27

    Setting up the Database (cont.)

    8. In the open file window, browse to the directory where the Eclipse SEF

    Workspace archive is extracted.

    9. Select the sql file to restore:

    \SEF\src\sef\module13\activity\SEF Activity.sql

    10. Click Open. This will close the open file window.

    11. Once in the Restore page, click Start Restore at the lower right portion of

    the UI.

    12. A dialog box displaying the progress bar will appear. Click Close once done.

  • 8/10/2019 M12 - JDBC

    28/31

    28

    Setting up the Database (cont.)

    13. At this point, the activity database containing all the tables and dataneeded in this activity has been successfully created.

    14. Closethe MySQL Administrator UI. Click the File Menu and then Close.

  • 8/10/2019 M12 - JDBC

    29/31

    29

    Questions and Comments

  • 8/10/2019 M12 - JDBC

    30/31

    30

    Activity

    1) Open Eclipse and navigate to

    sef.module13.activity.

    2) Take a note of AccountDAO and its

    implementing class AccountDAOImpl.

    Complete the implementation of

    AccountDAOImpl.

    3) Run The AccountDAOTest Unit test toverify your results.

  • 8/10/2019 M12 - JDBC

    31/31

    Appendix

    MySQL Version : 5.0

    License : http://www.opensource.org/licenses/gpl-license.php

    http://www.opensource.org/licenses/gpl-license.phphttp://www.opensource.org/licenses/gpl-license.phphttp://www.opensource.org/licenses/gpl-license.phphttp://www.opensource.org/licenses/gpl-license.php