You are on page 1of 31

Java Course

Module 12 Core Java API: JDBC

Module Objectives
At the end of this module, participants will be
able to:
Use JDBC technology and describe its features.
Use Database drivers and describe their
features.
Establish a connection to a database using the
Connection object.

Create and execute SQL statements in Java and


manipulate data resulting from executed SQL
statements.
Define the concept of Database Access Objects.

JDBC Overview
JDBC (Java Database Connectivity) is the Java industry
standard for database-independent connectivity between the
Java language and other databases.
JDBC provides a comprehensive API that provides the
application the ability to connect to databases, send SQL
statements, and process results.

Database Drivers
Database Drivers or JDBC
Drivers are required to connect
to different databases. The
JDBC requires different drivers
for each database.
JDBC drivers provide the
connection to the database and
implement the protocol
necessary for sending queries
and retrieving results.

Application

JDBC API

JDBC Driver

Database

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

Retrieving a Connection Object


A Connection object defines a connection or session with a
specific database.
It is where SQL statements are executed and results are
returned.
Before a Connection object can be used, the
java.sql.Connection class has to be imported first.

Retrieving a Connection Object (cont.)


A database driver can be loaded by using the
Class.forName() method.
Syntax :

Class.forName(JDBCDriver_Name);

Example :

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

A Connection object has three (3) important parts:


The URL or location of the data source
The username
The password

Retrieving a Connection Object (cont.)


A connection can be established by using the
getConnection() 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

Creating Query Statements


A Statement is the message that the JDBC sends to the data
source to either manipulate or request data from the data
source.
Before a Statement object can be used, the
java.sql.Statement class has to be imported first.

Creating Query Statements (cont.)


A Statement is created by using the following syntax:
Syntax :

Statement <identifier> = <Connection_Object>.createStatement();

Sample :

Connection myConn = DriverManager.getConnection();


Statement myStatement = myConn.createStatement();

A Statement needs to use a Connection object to identify


which connection the statement will be associated with.

10

Creating Query Statements (cont.)


A Statement can be executed by using either the
execute(), executeQuery() and executeUpdate()
methods.
Syntax :

<Statement_Object>.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

11

Basic SELECT Statement


Use the SELECT statement to retrieve data from one or more tables:
SELECT <column(s) >
FROM <table(s)>
[WHERE <condition>]
[ORDER BY <column(s) [ASC|DESC]>]
(select) column the names of the columns in the table to be selected.
Table the names of the tables where data are to be selected.
condition identifies the rows to be selected which contains expressions,
constraints, sub-queries, and comparison operators.
(order by) column the names of the columns used for sorting.
Note: where and order by are optional. Optional is represented by [ ]
Order by implicitly use ascending (ASC)
SELECT firstname FROM user;
SELECT firstname, lastname FROM user WHERE firstname = Luis ORDER BY
lastname;
SELECT firstname FROM user ORDER BY firstname DESC

12

Basic SELECT Statement (cont.)


To retrieve data from two or more tables, the column name
should be appended by the table name.
Syntax:
<table name>.<column name>

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

Aliasing is used to shorten the statement.


Syntax:
<table name> <alias>
<alias>.<column name>

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

13

Basic INSERT Statement


Use the INSERT statement to add data to a specific table:
INSERT INTO <table>
[ (<column(s)> ) ]
VALUES
(<value(s)>)
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 user VALUES (Luis, Chua)
INSERT INTO user (firstname, lastname) VALUES (Luis, Chua)

14

Basic UPDATE Statement


Use the UPDATE statement to change column values in a specific table:
UPDATE
SET
[WHERE

<table>
<column> = <value>
[, <column> = <value>, ]
<condition>]

table - the name of the table.


column - the name of the column where the new value is to be assigned.
value the new value for the column.
condition - identifies the rows to be updated which contains expressions,
constraints, sub-queries, and comparison operators.
Note: condition is optional. Optional is represented by [ ]
UPDATE user SET firstname = Aleli;
UPDATE user SET firstname = Aleli, lastname = Zapanta WHERE firstname =
Manny;

15

Basic DELETE Statement


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

FROM <table>
<condition>] ;

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;

16

Creating Query Statements


After a Statement has been executed, it returns different kinds
of data depending on the type of execute used.
execute() returns a boolean value and is used to execute
SQL statements written as a String object.
executeUpdate() returns an int value pertaining to the
number of rows affected and is used to execute DDL SQL
statements.
executeQuery() returns a ResultSet object and is used to
execute SELECT SQL statements.

17

Transactions
Transaction management is vital for operations that modify or
update 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-back
to undo the changes that were made.

18

Transactions (cont.)
Setting the Connection.autocommit() field of the Connection
object 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.

19

Using PreparedStatement
PreparedStatement is a Java object, which represents a
precompiled SQL statement.
PreparedStatement is 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, the
java.sql.PreparedStatement class has to be imported
first.

20

Using PreparedStatement (cont.)


A PreparedStatement is useful when an SQL statement has
to be executed multiple times.
A PreparedStatement is precompiled, hence it is immediately
executed by the DBMS, unlike Statement, which has to be
compiled first.
Syntax :
PreparedStatement <identifier> = <connection>.prepareStatement(<SQL Statement
goes here>");
Example :
Connection myConn = DriverManager.getConnection();
PreparedStatement pStmt = myConn.prepareStatement(Select * from Dogs Where
breed = ?);

21

Using PreparedStatement (cont.)


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

The wildcard can be replaced by using the appropriate methods


for a particular data type, including but not limited to:

setString()
setInt()
setDouble()
setDate()

** Refer to the PreparedStatementSample.java sample code

22

Using PreparedStatement (cont.)


The PreparedStatement object also has the different
execution commands as the Statement object, yielding similar
results.

23

Questions and Comments

24

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.

25

Setting up the Database (cont.)


5.
6.
7.

Type in the root password entered during installation as the password then
click OK. Once verified, the MySQL Administrator UI will be displayed.
In the left pane of the UI, click the Restore option. This will display the
Restore page.
Click the Open Backup File button found at the lower right portion of the UI.

26

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 Workspace>\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.

27

Setting up the Database (cont.)


13. At this point, the activity database containing all the tables and data
needed in this activity has been successfully created.
14. Close the MySQL Administrator UI. Click the File Menu and then Close.

28

Questions and Comments

29

Activity
1)
2)

3)

Open Eclipse and navigate to


sef.module13.activity.
Take a note of AccountDAO and its
implementing class AccountDAOImpl.
Complete the implementation of
AccountDAOImpl.
Run The AccountDAOTest Unit test to
verify your results.

30

Appendix
MySQL
Version
License

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

You might also like