Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Advanced Programming CH3

The document provides an overview of Java Database Connectivity (JDBC), detailing its purpose, components, and programming steps. It explains the types of JDBC drivers, how to establish database connections, and the use of statements and result sets for executing SQL commands and processing data. Key classes and methods related to JDBC are also discussed, including DriverManager, Connection, Statement, and ResultSet, along with their functionalities and usage examples.

Uploaded by

temsgentesfaye1
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Advanced Programming CH3

The document provides an overview of Java Database Connectivity (JDBC), detailing its purpose, components, and programming steps. It explains the types of JDBC drivers, how to establish database connections, and the use of statements and result sets for executing SQL commands and processing data. Key classes and methods related to JDBC are also discussed, including DriverManager, Connection, Statement, and ResultSet, along with their functionalities and usage examples.

Uploaded by

temsgentesfaye1
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

WOLAITA SODO UNIVERSITY DAWURO

TARCHA CAMPUS DEPARTMENT OF IT

Advanced Programming

Java Database Programming


Contents
• Overview of JDBC
• JDBC Drivers
• Statements and Prepared Statements
• Connecting to a Database
Overview of JDBC
– JDBC is a specification that provides a complete set of interfaces
and classes that allows for portable access to an underlying database.
– Using JDBC you can send SQL statements to almost any relational
database.
– JDBC is a Java API for executing SQL statements and supports
basic SQL functionality.
– It provides RDBMS access by allowing you to embed SQL inside
Java code.
– The JDBC library includes APIs for each of the tasks commonly
associated with database usage:
• Making a connection to a database
• Creating SQL or MySQL statements
• Executing that SQL or MySQL queries in the database
• Viewing & Modifying the resulting records
Overview of JDBC (contd)
– The JDBC Classes and Interfaces are in the java.sql package
What does JDBC do?
• Establish a connection with a database
• Send SQL statements
• Process the results
Steps in using JDBC
1. Load the JDBC driver
2. Define the Connection URL
3. Establish the Connection
4. Create a Statement object
5. Execute a query
6. Process the results
7. Close the connection
JDBC Model

Application JDBC Driver

How It Works
– 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
– Ideal: can change database engines without changing any
application code (not always in practice)
JDBC Model (cont)
– JDBC consists of two parts:
• The JDBC API
• JDBC Driver Manager, which
communicates with vendor-
specific drivers that interact
with the database
JDBC Model(cont)

Oracle
Driver

Oracle

Java JDBC DB2


Application Driver

DB2
Network
MySQL
Driver

MySQL
JDBC Driver Types
– JDBC drivers implement the defined interfaces
in the JDBC API for interacting with your
database server.
– For example, using JDBC drivers enable you to
open database connections and to interact with it
by sending SQL or database commands then
receiving results with Java.
– The Java.sql package contains various classes
with their behaviors defined and their actual
implementaions are done in third-party drivers.
Third party vendors implements the
java.sql.Driver interface in their database driver.
JDBC Driver Types(cont)
Type Description

JDBC-to-ODBC Bridge Driver – connects Java to a


1
Microsoft ODBC (Open Database Connectivity) data source.
Native-API, Part Java Drivers – enable JDBC programs to
use database-specific APIs (normally written in C or C++) that
2
allow client programs to access databases via the Java Native
Interface.
JDBC-Net Pure Java Drivers – take JDBC requests and
translate them into a network protocol that is not database
3
specific. These requests are sent to a server, which translates
the database requests into a database-specific protocol.
Native-protocol Pure Java Drivers – convert JDBC requests
4 to database-specific network protocols, so that Java programs
can connect directly to a database.
1. Application
causes driver to be
loaded Java application
2. Application asks DriverManager
for a connection to a particular DB.
3. DriverManager DriverManager asks all loaded
gives connection drivers, and one of them responds
to the application. with a connection.

java.sql.package
java.sql.DriverManager
(JDBC library)

4. Connection
supplied by
Driver for MySQL Driver for Oracle DriverManager is
databases databases used by
application to talk
How JDBC establishes a JDBC through
connection between your the driver to the
MySQL
code and a database database.
DB
JDBC Programming Steps

Connect 1) Register the driver


2) Create a connection to the database

Query 1) Create a statement


2) Query the database

Process Results 1) Get a result set


2) Assign results to Java variables

1) Close the result set


Close 2) Close the statement
3) Close the connection
Primary JDBC classes
– Java classes used for JDBC
• DriverManager: used to load the class which is the driver for a
specific database.
• Connection: the database connection interface.
• Statement: An SQL statement to be executed on the
connection.
• ResultSet: The set of results that are returned by a query.
• DataSource: interface can be used for any object that can be
used as a database connection.
JDBC - Statements
– Once a connection is obtained we can interact
with the database.
– The JDBC Statement, CallableStatement, and
PreparedStatement interfaces define the methods
and properties that enable you to send SQL
commands and receive data from your database.
– They also define methods that help bridge data
type differences between Java and SQL data types
used in a database.
JDBC - Statements
Interfaces Recommended Use

Use for general-purpose access to your database.


Useful when you are using static SQL statements
Statement
at runtime. The Statement interface cannot
accept parameters.

Use when you plan to use the SQL statements


PreparedStatement many times. The PreparedStatement interface
accepts input parameters at runtime.

Use when you want to access database stored


CallableStatement procedures. The CallableStatement interface can
also accept runtime input parameters.
The Statement Objects
Creating Statement Object:
• you need to create a statement using the Connection object's createStatement( ) method,
as in the following example:
Closing Statement Object:
• Just as you close a Connection object to save database resources, for the same reason you
should also close the Statement object.
• A simple call to the close() method will do the job.
Example:
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try{
stmt = con.createStatement();
stmt.execute("INSERT INTO StudentInfo VALUES (1,'Atnafu')");
}
catch (SQLException e) { }
finally {
stmt.close();
}
The Statement Objects:
– Once you've created a Statement object, you can then
use it to execute a SQL statement with one of its
three execute methods.
1. boolean execute(String SQL) : Returns a boolean value of
true if a ResultSet object can be retrieved; otherwise, it
returns false.
2. int executeUpdate(String SQL) : Returns the numbers of
rows affected by the execution of the SQL statement. Use
this method to execute SQL statements for which you expect
to get a number of rows affected - for example, an INSERT,
UPDATE, or DELETE statement.
3. ResultSet executeQuery(String SQL) : Returns a ResultSet
object. Use this method when you expect to get a result set,
as you would with a SELECT statement.
The PreparedStatement Objects
• The PreparedStatement interface extends the Statement interface
which gives you added functionality with a couple of advantages over
a generic Statement object.
• This statement gives you the flexibility of supplying arguments
dynamically.
Creating PreparedStatement Object:
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
}
catch (SQLException e) {
...
}finally { . . .}
The PreparedStatement Objects
Closing PreparedStatement Obeject:
• A simple call to the close() method will close the prepared statement.

PreparedStatement pstmt = null;


try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
...
}catch (SQLException e) {
...
}
finally {
pstmt.close();
}
Some Popular JDBC Drivers
RDBMS JDBC Driver Name
Driver Name : com.mysql.jdbc.Driver
MySQL Database URL format:
jdbc:mysql//hostname/databaseName
Driver Name : oracle.jdbc.driver.OracleDriver
Oracle Database URL format:
jdbc:oracle:thin@hostname:portnumber:databaseName
Driver Name : com.ibm.db2.jdbc.net.DB2Driver
DB2 Database URL format:
jdbc:db2:hostname:portnumber/databaseName
Driver Name : com.jdbc.odbc.JdbcOdbcDriver
Access Database URL format:
jdbc:odbc:databaseName
Driver Name : com.org.derby.jdbc.ClintDriver
Java DB Database URL format:
jdbc:derby:databaseName
JDBC - Result Sets
– The SQL statements that read data from a database query return
the data in a result set.
– The rows that satisfy a particular query are called the result set.
– A user can access the data in a result set using a cursor one row at
a time from top to bottom
– The java.sql.ResultSet interface represents the result set of a
database query.
– A ResultSet object maintains a cursor that points to the current row
in the result set.
– ResultSet interface methods can be broken down into three
categories:
• Navigational methods: used to move the cursor around.
• Get methods: used to view the data in the columns of the current row being
pointed to by the cursor.
• Update methods: used to update the data in the columns of the current row.
The updates can then be updated in the underlying database as well.
JDBC - Result Sets
– JDBC provides following connection methods to create
statements with desired ResultSet:
1. createStatement(int RSType, int RSConcurrency);
2. prepareStatement(String SQL, int RSType, int RSConcurrency);
3. prepareCall(String sql, int RSType, int RSConcurrency);

– The first argument indicate the type of a ResultSet object and the
second argument is one of two ResultSet constants for specifying
whether a result set is read-only or updatable.
JDBC - Result Sets
Type of ResultSet:
• The possible RSType are given below, If you do not specify any ResultSet type,
you will automatically get one that is TYPE_FORWARD_ONLY.

Type Description

ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set.

The cursor can scroll forwards and backwards, and


the result set is not sensitive to changes made by
ResultSet.TYPE_SCROLL_INSENSITIVE
others to the database that occur after the result set
was created.

The cursor can scroll forwards and backwards, and


the result set is sensitive to changes made by others to
ResultSet.TYPE_SCROLL_SENSITIVE.
the database that occur after the result set was
created.
JDBC - Result Sets
Concurrency of ResultSet:
• The possible RSConcurrency are given below, If you do not specify any Concurrency
type, you will automatically get one that is CONCUR_READ_ONLY.

Concurrency Description

Creates a read-only result set. This is the


ResultSet.CONCUR_READ_ONLY
default

ResultSet.CONCUR_UPDATABLE Creates an updateable result set.


Example:
try {
Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
}
catch(Exception ex) { .... }
finally {....}
JDBC - Result Sets
Navigating a Result Set:
• There are several methods in the ResultSet interface that involve moving the
cursor, including:

S.N. Methods & Description

public void beforeFirst() throws SQLException


1
Moves the cursor to just before the first row

public void afterLast() throws SQLException


2
Moves the cursor to just after the last row

public boolean first() throws SQLException


3
Moves the cursor to the first row

public void last() throws SQLException


4
Moves the cursor to the last row.

public boolean absolute(int row) throws SQLException


5
Moves the cursor to the specified row
JDBC - Result Sets
Navigating a Result Set:
S.N. Methods & Description
public boolean relative(int row) throws SQLException
6 Moves the cursor the given number of rows forward or backwards from where it currently is
pointing.
public boolean previous() throws SQLException
7 Moves the cursor to the previous row. This method returns false if the previous row is off the
result set
public boolean next() throws SQLException
8 Moves the cursor to the next row. This method returns false if there are no more rows in the
result set
public int getRow() throws SQLException
9
Returns the row number that the cursor is pointing to.
public void moveToInsertRow() throws SQLException
10 Moves the cursor to a special row in the result set that can be used to insert a new row into the
database. The current cursor location is remembered.
public void moveToCurrentRow() throws SQLException
11 Moves the cursor back to the current row if the cursor is currently at the insert row; otherwise,
this method does nothing
JDBC - Result Sets
Viewing a Result Set:
• The ResultSet interface contains dozens of methods for getting the data of the
current row.
• There is a get method for each of the possible data types, and each get method
has two versions:
1. One that takes in a column name.
2. One that takes in a column index.
• For example, if the column you are interested in viewing contains an int, you
need to use one of the getInt() methods of ResultSet:

S.N. Methods & Description

public int getInt(String columnName) throws SQLException


1
Returns the int in the current row in the column named columnName

public int getInt(int columnIndex) throws SQLException


2 Returns the int in the current row in the specified column index. The column index starts at 1,
meaning the first column of a row is 1, the second column of a row is 2, and so on.
JDBC - Result Sets
• Similarly there are get methods in the ResultSet interface for each of the eight
Java primitive types, as well as common types such as java.lang.String,
java.lang.Object, and java.net.URL
• There are also methods for getting SQL data types java.sql.Date, java.sql.Time,
java.sql.TimeStamp, java.sql.Clob, and java.sql.Blob.
ResultSet Methods
• String getString(int columnIndex)
• boolean getBoolean(int columnIndex)
• byte getByte(int columnIndex)
• short getShort(int columnIndex)
• int getInt(int columnIndex)
• long getLong(int columnIndex)
• float getFloat(int columnIndex)
• double getDouble(int columnIndex)
• Date getDate(int columnIndex)
• Time getTime(int columnIndex)
• Timestamp getTimestamp(int columnIndex)
JDBC - Result Sets
ResultSet Methods
• isNull
– In SQL, NULL means the field is empty
– Not the same as 0 or “”
– In JDBC, you must explicitly ask if a field is null by calling
ResultSet.isNull(column)

• getMaxRows/setMaxRows
– Maximum number of rows a ResultSet may contain
– Unless explicitly set, the number of rows is unlimited
JDBC - Result Sets
Updating a Result Set:
• The ResultSet interface contains a collection of update methods for updating
the data of a result set.
• As with the get methods, there are two update methods for each data type:
1. One that takes in a column name.
2. One that takes in a column index.
• For example, to update a String column of the current row of a result set, you
would use one of the following updateString() methods:

S.N. Methods & Description

public void updateString(int columnIndex, String s) throws SQLException


1
Changes the String in the specified column to the value of s.

public void updateString(String columnName, String s) throws SQLException


2 Similar to the previous method, except that the column is specified by its name instead of
its index.
JDBC - Result Sets
Updating a Result Set:
• There are update methods for the eight primitive data types, as well as String, Object,
URL, and the SQL data types in the java.sql package.
• Updating a row in the result set changes the columns of the current row in the
ResultSet object, but not in the underlying database. To update your changes to the row
in the database, you need to invoke one of the following methods.
S.N. Methods & Description
public void updateRow()
1
Updates the current row by updating the corresponding row in the database.
public void deleteRow()
2
Deletes the current row from the database
public void refreshRow()
3
Refreshes the data in the result set to reflect any recent changes in the database.
public void cancelRowUpdates()
4
Cancels any updates made on the current row.
public void insertRow()
5 Inserts a row into the database. This method can only be invoked when the cursor is pointing to
the insert row.
End of Ch.3

You might also like