You are on page 1of 47

CHAPTER SIX

JAVA DATABASE CONNECTIVITY(JDBC)


Outline
2

Introduction
JDBC driver types
Steps to Connect to the Database
Transactions and JDBC
Introduction to Java JDBC
3
◦ Java JDBC is a java API to connect and execute query with the database.
◦ JDBC API uses jdbc drivers to connect with the database.

◦ Stands for Java DataBase Connectivity


◦ JDBC is used for accessing databases from Java applications.
◦ Information is transferred from relations to objects and vice-
versa.
◦ databases optimized for searching/indexing
◦ objects optimized for engineering/flexibility
Why use JDBC
4

 Before JDBC, ODBC API was the database API to


connect and execute query with the database.

 But, ODBC API uses ODBC driver which is written in


C language (i.e. platform dependent and unsecured).
That is why Java has defined its own API (JDBC API)
that uses JDBC drivers (written in Java language).
JDBC Driver types
5
JDBC Driver is a software component that enables
java application to interact with the database.
There are four types of drivers:
 JDBC Type 1 Driver -- JDBC/ODBC Bridge drivers
 ODBC (Open DataBase Connectivity) is a standard software API
designed to be independent of specific programming languages
 Sun provides a JDBC/ODBC implementation
 JDBC Type 2 Driver -- use platform-specific APIs for
data access
 JDBC Type 3 Driver -- 100% Java, use a net protocol
to access a remote listener and map calls into vendor-
specific calls
 JDBC Type 4 Driver -- 100% Java
 Most efficient of all driver types
JDBC DRIVER MODEL
6
JDBC Architecture
7

Oracle
Driver

Oracle

Java SQLserver
Application JDBC Driver

SQLServer
Network

MySQL
Driver

MySQL
JDBC Architecture (cont.)
8

• Java code calls JDBC library


• JDBC loads a driver
• Driver talks to a particular database
• An application can work with several databases by using all corresponding
drivers
JDBC Driver for MySQL (Connector/J)
9

Connector/J is a JDBC Type 4 Driver for connecting


Java to MySQL
Installation is very simple:
 Download the “Production Release” ZIP file from
http://dev.mysql.com/downloads/connector/j/3.1.html
 Unzip it
 Put the JAR file where Java can find it
 Add the JAR file to your CLASSPATH, or
 In Eclipse: Project --> Properties --> Java Build Path --> Libraries -->
Add External Jars...
10

S T E P S T O C O N N E C T T O T H E D A T A BA S E
Seven Steps
11

1.First, make sure the DMBS (i.e MySQL) server is running


2. second, write your java program based on the following steps.
A. Importing Packages
B. Registering the JDBC Drivers
C. Opening a Connection to a Database
D. Creating a Statement Object
E. Executing a Query and Returning a Result Set Object
F. Processing the Result Set
G. Closing the Result Set and Statement Objects
H. Closing the Connection
1. Import JDBC packages
12

 Import statements at the beginning of your program:


 import java.sql.Connection;
 import java.sql.SQLException;
or
 import java.sql.*;
2. Registering the Driver
13

 Load the driver class only. The class has a static initialization
block that makes an instance and registers it with the
DriverManager.
try {
Class.forName("com.mysql.jdbc.Driver");
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException cnfe) {
System.out.println("Error loading driver: " + cnfe);
}
3. Open a Connection to a Database
14

A call to this method creates an object instance of the java.sql.Connection class.

The getConnection() method is an overloaded method that takes


• Three parameters, one each for the URL, username, and password
• Only one parameter for the database URL. In this case, the URL contains
the username and password

Connection conn = DriverManager.getConnection(URL, username,


passwd); Or
Connection conn = DriverManager.getConnetion(URL);
where URL, username and password are of String data types.
4. Querying the Database or create a
query object
15

Querying the database involves the following steps:

– Creating a Statement Object


This is to instantiate objects that run the query against the database to which they are connected.
This is done by the createStatement() method of the conn Connection object created
above. A call to this method creates an object instance of the Statement class.

Statement sql_stmt = conn.createStatement();


Or

Creating a PreparedStatement
A PreparedStatement is associated as a channel with a connection and a compiled SQL
statement. PreparedStatements are also created with a Connection method. The following snippet
shows how to create a parameterized SQL statement with three input parameters:

PreparedStatement prepareUpdatePrice = conn.prepareStatement( "UPDATE


Sells SET price = ? WHERE bar = ? AND beer = ?");
Cont…
16

Statements are used to send queries or commands.


 Statement has three methods to execute a SQL statement:
 executeQuery() for QUERY statements
 Returns a ResultSet which contains the query results
 executeUpdate() for INSERT, UPDATE, DELETE, or DDL statements
 Returns an integer, the number of affected rows from the SQL
 execute() for either type of statement
SQL CREATE Statement
17
SQL INSERT Statement
18
SQL UPDATE Statement
19
20
21

• Execute a select statement


Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery
("select RENTAL_ID, STATUS from ACME_RENTALS");

 Execute a delete statement


Statement stmt = conn.createStatement();
int rowcount = stmt.executeUpdate
("delete from ACME_RENTAL_ITEMS
where rental_id = 1011");
5. Executing the Query and Returning a ResultSet
22

This is done by using the executeQuery() method of the Statement


object. A call to this method takes as parameter a SQL SELECT
statement and returns a JDBC ResultSet object.
ResultSet rset = sql_stmt.executeQuery
(“SELECT empno, ename, sal, deptno FROM emp ORDER BY ename”);
Execute a Query
23

Idea
– statement.executeQuery("SELECT … FROM …");
• This version returns a ResultSet
– statement.executeUpdate("UPDATE …");
– statement.executeUpdate("INSERT …");
– statement.executeUpdate("DELETE…");
– statement.execute("CREATE TABLE…");
– statement.execute("DROP TABLE …");
But those returns the number of affected rows not resultset
Cont…
24

 Example
String query = "SELECT col1, col2, col3 FROM sometable";
ResultSet resultSet = statement.executeQuery(query);

 Note:- possible to use createstatement() for all types of database operations


with different executer functions.

 Before closing the connection U should close the objects of any statement.
ResultSet Object
25

The results of executing an SQL query are returned in the form of an


object that implements the ResultSet interface
•ResultSet object contains a “cursor” that points to a particular record
(called the current record)
•When the ResultSet object is created, the cursor points to the position
immediately preceeding the first record
•Several methods available to navigate the ResultSet by moving the
cursor
–first(), last(), beforeFirst(), afterLast(), next(), previous(),etc. //returns
true if the move is successful
–isFirst() //whether you reached the beginning of the ResultSet
–isLast()// whether you reached the end of the ResultSet
Cont…
26
6. Process the Result Set
27
Once the query has been executed, there are two steps to be
carried out:
– Processing the output resultSet to fetch the rows
next() method of the ResultSet object
– Retrieving the column values of the current row

getXXX() methods of the JDBC rset object


Here getXXX() corresponds to the getInt(), getString() etc with XXX
being replaced by a Java datatype
while (rset.next())
System.out.println (rset.getString(“ename”));
Cont…
28

 next() returns TRUE if there are still remaining records


Cont…
29

• Example
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(“SELECT ID, name, score FROM table1”);
NOTE
While (rs.next()){ You must step the cursor to the first record before
int id = rs.getInt(“ID”); read the results
This code will not skip the first record
String name = rs.getString(“name”);
float score = rs.getFloat(“score”);
System.out.println(“ID=” + id + “ ” + name + “ ” + score);}

Output
ID name score ID=1 James 90.5
1 James 90.5 ID=2 Smith 45.7
2 Smith 45.7 ID=3 Donald 80.2
3 Donald 80.2
Table1
Cont…
30

Important ResultSet methods


– resultSet.next()
• Goes to the next row. Returns false if no next row.
– resultSet.getString("columnName")
• Returns value of column with designated name in current
row, as a String. Also getInt, getDouble, getBlob, etc.
– resultSet.getString(columnIndex)
• Returns value of designated column. First index is 1 (ala
SQL), not 0 (ala Java).
– resultSet.beforeFirst()
• Moves cursor before first row, as it was initially.
– resultSet.absolute(rowNum)
• Moves cursor to given row (starting with 1).
Cont…
31

Assumption
– Query was “SELECT first, last, address FROM…”
• Using column names
while(resultSet.next()) {
System.out.println(
"First name: , last name:, address: \n",
resultSet.getString("first"),
resultSet.getString("last"),
resultSet.getString("address"));
}
Cont…
32

• Using column indices


while(resultSet.next()) {
System.out.printf( "First name:, last name:, address: \n",
resultSet.getString(1),
resultSet.getString(2),
resultSet.getString(3)); }
7. Closing the ResultSet and Statement
33

Once the ResultSet and Statement objects have been used, they
must be closed explicitly. This is done by calls to the close() method
of the ResultSet and Statement classes.
rset.close();
sql_stmt.close();

If not closed explicitly, there are two disadvantages:


– Memory leaks can occur
– Maximum Open cursors can be exceeded
8. Closing the Connection
34

The last step is to close the database connection. This is done by a call to the
close() method of the Connection class.

conn.close();// explicitly connection pool utility


Examples
35

 It is a good idea to close the Statement and Connection objects


when you have finished with them
 Close the ResultSet object
rs.close();
 Close the Statement object
stmt.close();
 Close the connection
connection.close();
A complete program
36
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/Emp","root","");
//here Emp is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
37

TRANSACTIONS AND JDBC


Transactions
38

 Transactions group multiple database operations to allow to


implement data consistency.
 Operations in a Transaction are ALL executed or NONE is
executed.
 Typical example:
– in an account transfer we have to perform two operations in the
database: one debit and one credit.
– either BOTH operations are performed or NONE is.
– we define them as part of the same transaction.
Cont…
39

 A transaction is a sequence of actions that must be considered as


a whole: it can be committed or rollbacked but cannot be
partially executed
 Today's DBMS products are technically sophisticated
securing data integrity in their databases and providing fast
access to data even to multiple concurrent users.
What is Transaction Control Language (TCL)?

40

 Used to manage the changes made by DML statements. It allows


statements to be grouped together into logical transactions.
 TRANSACTION CONTROL refers to the commands that allow
you to save, or not, any data that you may have manipulated.
Client/Server Concepts in SQL Environment

41
Cont…
42

– if there is an error after debiting but before crediting we can tell


the db to restore the information that existed BEFORE the
transaction begun. --> ROLLBACK.
– whenever the transaction is finished with no errors we COMMIT
the changes.
– after committing the changes we cannot rollback anymore.
Cont…
43

 By default, after each SQL statement is executed the changes are


automatically committed to the database
 Turn auto-commit off to group two or more statements together
into a transaction
connection.setAutoCommit(false);
 Call commit to permanently record the changes to the database
after executing a group of statements
– after committing the changes we cannot rollback anymore.
– Call rollback if an error occurs
Transactions: Example
44

Connection connection =
DriverManager.getConnection(url, userProperties);
connection.setAutoCommit(false);
try {
statement.executeUpdate(...);
statement.executeUpdate(...);
...
connection.commit();
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException sqle) {
// report problem
}
} finally {
try {
connection.close();
} catch (SQLException sqle) { }
}
Useful Connection Methods (for Transactions)
45

getAutoCommit/setAutoCommit
– By default, a connection is set to auto-commit
– Retrieves or sets the auto-commit mode
• commit
– Force all changes since the last call to commit to become
permanent
– Any database locks currently held by this Connection
object are released
• rollback
– Drops all changes since the previous call to commit
– Releases any database locks held by this Connection
object
Cont…
46
47

Thank you

You might also like