You are on page 1of 18

IFS2203–

Object Oriented Programming

- JDBC -
Inte Christinawati Bu’ulӧlӧ
0118118201
Topics
 JDBC
 JDBC Drivers
 Basic Step To Connect to Database
 Hibernate Advantages
 Transaction and JDBC
 Handling Errors with Exceptions

12/19/2019 ICB/PBO 2
JDBC
• Dynamic application requires a
persistent data storage. Files
and database are available
options.
• JDBC (Java Database
Connectivity) API allows Java
programs to connect to
databases. Includes two
packages:
• java.sql package
• javax.sql package (adds server-
side capabilities)
12/19/2019 ICB/PBO 3
JDBC Drivers
• The JVM uses a JDBC driver to
translate generalized JDBC calls into
vendor specific database calls.
• There are 4 types of JDBC Drivers
• Type 1 - JDBC-ODBC Bridge
• Type 2 - JDBC-Native Bridge
• Type 3 - JDBC-Net Bridge
• Type 4 - Direct JDBC Driver: Pure Java.
JDBC driver converts directly to
native API and sends through vendor
specific network protocol (great for
intranets).

12/19/2019 ICB/PBO 4
Basic steps to use a database in Java
1.Establish a connection
2.Create JDBC Statements
3.Execute SQL Statements
4.GET ResultSet
5.Close connection

12/19/2019 ICB/PBO 5
Establish a Connection
• First, import java.sql.*; Type 4 JDBC Driver – Oracle Server
Class.forName (“oracle.jdbc.driver.OracleDriver”);
• Load the vendor specific Connection con = DriverManager.getConnection (
driver “jdbc:oracle:thin:@bonsai.ite.gmu.edu:1521:ite”,
• Make connection. “accountname",
“password”);

Type 4 JDBC Driver – MySQL Server


Class.forName (“com.mysql.jdbc.Driver”);
Connection con = DriverManager.getConnection (
“jdbc:oracle:thin:@bonsai.ite.gmu.edu:1521:ite”,
“accountname",
“password”);

12/19/2019 ICB/PBO 6
Create and Execute JDBC Statements (1)
• Creates a Statement object for sending SQL statements to the
database.
Statement stmt = con.createStatement() ;

• Execute it to get an object of ResultSet class, which is representing a


database result set.
• executeQuery() is used for reading
• executeUpdate() for manipulating data and
• execute() if you are not sure.

Statement stmt = con.createStatement();


stmt.executeUpdate ( "INSERT INTO COFFEES " + "VALUES ('Colombian', 101, 7.99, 0, 0)");
12/19/2019 ICB/PBO 7
Create and Execute JDBC Statements (2)
createStatement (int resultSetType, int resultSet)

resultSetType:
• TYPE_FORWARD_ONLY — The cursor can only move forward in the result set.
• TYPE_SCROLL_INSENSITIVE — The cursor can scroll forward and backward, and
the result set is not sensitive to changes made by others to the database that
occur after the result set was created.
• TYPE_SCROLL_SENSITIVE — The cursor can scroll forward and backward, and the
result set is sensitive to changes made by others to the database that occur after
the result set was created.
resultSetConcurrency:
• CONCUR_READ_ONLY
• CONCUR_UPDATABLE
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
12/19/2019 ICB/PBO 8
Create and Execute JDBC Statements (3)

//other codes

12/19/2019 ICB/PBO 9
Execute SQL Statements (1)

• An object of ResultSet class representing a database query result set.


It is generated as the result of statement execution.
String query = "select * from Student"; ResultSet methods:
- next()
ResultSet rs = stmt.executeQuery(query); - previous()
while (rs.next()) { - first()
int ssn = rs.getInt("SSN"); - last()
String name = rs.getString("NAME");
int marks = rs.getInt("MARKS"); - isLast()
} - isFirst()

12/19/2019 ICB/PBO 10
Execute SQL Statements (2)
• ResultSetMetaData
• If you have to get metadata of a table like total number of column, column
name, column type etc. , ResultSetMetaData is useful because it provides
methods to get metadata from the ResultSet object.

ResultSetMetaData rsmtadta = rs.getMetaData();


int colCount = rsmtadta.getColumnCount();
String colName = rsmtadta.getColumnName();

12/19/2019 ICB/PBO 11
Close Connection
rs.close();
stmt.close();
con.close();

• Do NOT close the connection


• The same connection object can be used to create further statements
• A Connection may only have one active Statement at a time. Do not forget to
close the statement when it is no longer needed.
• Close the connection when you no longer need to access the
database

12/19/2019 ICB/PBO 12
try{

}
catch(SQLException sqle){
System.out.println("Terjadi kesalahan: " +
sqle.getMessage());
12/19/2019 ICB/PBO 13
}
Transactions and JDBC (1)
• one or more SQL statements that may be grouped together as a
single processing entity
• We want either all the statements or none of them to be
executed.
• Java provides the Connection interface methods
• commit  used at the end of a transaction to commit/finalise the
database changes
• rollback  used to restore the database to the state it was in prior to
the current transaction

12/19/2019 ICB/PBO 14
Transactions and JDBC (2)
• By default, JDBC automatically commits each individual SQL
statement that is applied to a database.
• In order to change this default behaviour so that transaction
processing may be carried out, we must first execute Connection
method setAutoCommit with an argument of false.
• We can then use methods commit and rollback to effect
transaction processing.

12/19/2019 ICB/PBO 15
Transactions and JDBC (3)

12/19/2019 ICB/PBO 16
Handling Errors with Exceptions
• Programs should recover and leave the database in a consistent state.
• If a statement in the try block throws an exception or warning, it can
be caught in one of the corresponding catch statements
• How might a finally {…} block be helpful here?
• E.g., you could rollback your transaction in a
catch { …} block or close database connection and free database
related resources in finally {…} block

12/19/2019 ICB/PBO 17
References
• https://docs.oracle.com/javase/tutorial/jdbc/
• https://www.javatpoint.com/java-jdbc

12/19/2019 ICB/PBO 18

You might also like