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

Chapter 7-Java Database Connectivity

The document discusses Java Database Connectivity (JDBC) and how to connect Java applications to databases. It covers SQL concepts and how to use JDBC to connect to a database, execute statements and queries, and retrieve and manipulate result sets.

Uploaded by

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

Chapter 7-Java Database Connectivity

The document discusses Java Database Connectivity (JDBC) and how to connect Java applications to databases. It covers SQL concepts and how to use JDBC to connect to a database, execute statements and queries, and retrieve and manipulate result sets.

Uploaded by

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

Chapter 7

Java Database Connectivity


Outline
 Introduction
SQL and JDBC Overview
Connecting to a Database
Manipulating Databases with JDBC
Prepared Statements
Scrollable and Updateable Result Sets
Transaction Processing
Introduction
• A database is an organized collection of data.
• A database management system(DBMS) provides
mechanisms for storing, organizing, retrieving and
modifying data for many users.
• DBMS allow for the access and storage of data With
out concern for the internal representation of data.
• Eg.
Microsoft SQL Server, Oracle, Sybase, IBM DB2,
nformix, PostgreSQL and MySQL
Cont..
• Java programs communicate with databases and
manipulate their data using the Java Database
Connectivity (JDBC) API.
• A JDBC driver enables Java applications to connect
to a database in a particular DBMS and allows you to
manipulate that database using the JDBC API.
SQL Overview
SELECT Query: SQL query “selects” rows and columns
from one or more tables in a database.
• performed by queries with the SELECT keyword.
• basic form: SELECT * FROM tableName asterisk (*)
wildcard character indicates that all columns from the
tableName table should be retrieve.
WHERE Clause: it’s necessary to locate rows in a database
that satisfy certain selection criteria. SQL uses the optional
WHERE clause in a query to specify the selection criteria
for the query. Basic form:
SELECT columnName1, columnName2, … FROM
tableName WHERE criteria
cont..
• ORDER BY Clause: The rows in the result of a query can
be sorted into ascending or descending order by using the
optional ORDER BY clause. The basic form of a query with
an ORDER BY clause is
SELECT columnName1, columnName2, … FROM
tableName ORDER BY column ASC|DESC
• INNER JOIN: operator, which merges rows from two
tables by matching values in columns that are common to
the tables. Basic form:
SELECT columnName1, columnName2,…FROM table1
INNER JOIN table2
ON table1.columnName = table2.columnName
Cont..
• INSERT Statement: inserts a row into a table.
• Basic form : INSERT INTO tableName ( columnName1,
columnName2, …, columnNameN )
VALUES ( value1, value2, …, valueN )
• UPDATE Statement: modifies data in a table.
• Basic form: UPDATE tableName SET columnName1 =
value1, columnName2 = value2,…,columnNameN =
valueN WHERE criteria
• DELETE Statement: removes rows from a table. Its basic
form is DELETE FROM tableName WHERE criteria
Reading Assignment
Between, IN,LIMIT
GROUP BY
 Like Clause
Left JOIN and right JOIN
ALTER, DROP, CREATE
DISTINCT statement
AND/OR Clause
IF, CASE and WHILE
COMMIT Statement
ROLLBACK Statement
TRUNCATE TABLE Statement
Basic JDBC Programming Concepts
• The classes that you use for JDBC programming are
contained in the java.sql and javax.sql packages.
• JDBC was developed by Sun Microsystems in late 90s
• JDBC provides database independent connectivity
between Java Applications and a wide range of
relational databases
• In general JDBC Architecture consists of two layers
• JDBC API: provides the application-to-JDBC
Manager connection.
• JDBC Driver API: Supports the JDBC Manager-
to-Driver Connection.
The architectural diagram, which shows the location of the
driver manager with respect to the JDBC drivers and the Java
application
Cont..
• The JDBC API uses a driver manager and database-specific
drivers to provide transparent connectivity to heterogeneous
databases.
• The JDBC driver manager ensures that the correct driver is
used to access each data source.
• The driver manager is capable of supporting multiple
concurrent drivers connected to multiple heterogeneous
databases.
Common JDBC Components
The JDBC API provides the following interfaces and
classes
1. DriverManager:
• This class manages a list of database drivers. Matches
connection requests from the java application with the
proper database driver using communication subprotocol.
The first driver that recognizes a certain subprotocol under
JDBC will be used to establish a database Connection.
2. Driver:
• This interface handles the communications with the database
server. You will interact directly with Driver objects very
rarely. Instead, you use DriverManager objects, which
manages objects of this type. It also abstracts the details
associated with working with Driver objects.
Cont..
3. Connection :
• This interface with all methods for contacting a database.
The connection object represents communication context,
i.e. all communication with database is through connection
object only.
4.Statement :
• You use objects created from this interface to submit the
SQL statements to the database. Some derived interfaces
accept parameters in addition to executing stored
procedures.
5. ResultSet:
• These objects hold data retrieved from a database after you
execute an SQL query using Statement objects. It acts as
an iterator to allow you to move through its data.
Cont..
6 SQLException:handles any errors that occur in a database
application
Manipulating Databases with JDBC requires three steps
1) Connect to a database
2) Query the database
3) Display the results of the query
Popular JDBC driver names and database URL
RDBMS JDBC driver name URL format
MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/databaseName

ORACLE
oracle.jdbc.driver.OracleDrive jdbc:oracle:thin:@hostname:port
r Number:databaseName

DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port Number/databaseName

jdbc:sybase:Tds:hostname: port
Sybase com.sybase.jdbc.SybDriver
Number/databaseName
1. Connecting to a Database
• The first step to establishing a connection using
JDBC involves registering the driver class.
• To do that, use the forName method of the Class
class, specifying the package and class name of the
driver. For example, to register the MySQL
connector:
Class.forName(“com.mysql.jdbc.Driver”);
• Note that the forName method throws
ClassNotFoundException, so you have to enclose
this statement in a try/catch block
Cont..
• After you register the driver class, you can call the
static getConnection method of the DriverManager
class to open the connection. This method takes
three String parameters: the database URL, the
user name, and a password. i.e
String url = “jdbc:mysql://localhost/databaseName”;
String user = “root”;
String pw = “pw”;
con = DriverManager.getConnection(url, user, pw);
• java.sql.Connection
• Represents a single logical DB connection; used for
sending SQL statements
2. Creating Statements
After you connect to a database, you get a
Connection object.
The Connection class contains the methods for
creating SQL statements.
Statement interface represents a SQL statement
There are three types of Statement objects
1. Simple Statements
 It represents a simple SQL statement.
Cont..
Connection interface methods for creating
Statement object
 public Statement createStatement() throws
SQLException. Creates a simple SQL statement.
The result set of this statement will be read-only
and forward scrolling only.
Statement statement =
connection.createStatement();
statement.executeUpdate(“INSERT INTO Employees
VALUES (101, 20.00,‘Gashaw’, ‘Alene’)”);
Cont..
• public Statement createStatement(int resltSetType, int
concurrency) throws SQLException.
• Creates a simple SQL statement whose result set will have
the given properties. The resultSetType is either
• TYPE_FOR-WARD_ONLY,
• TYPE_SCROLL_INSENSITIVE, or
• TYPE_SCROLL_SENSITIVE, which are static fields in
the java.sql.ResultSet interface.
• The concurrency type is CONCUR_READ_ONLY or
CONCUR_UPDATABLE, for denoting whether the
Resultset is updatable or not.
Prepared Statements

• It contains parameters and used to represent a prepared


SQL statement.
• Before a prepared statement can be executed, each
parameter needs to be assigned using one of the set methods
in the Prepared Statement interface.
• A question mark(?) is used to denote a parameter
• i.e. INSERT INTO Employees VALUES (?, ?, ?, ?)
• Prepared statements are preferred over simple statements
for two reasons:
 execute faster because they are precompiled.
 easier to code
Cont...
• public PreparedStatement prepareStatement(String sql)
Preparing statement
throws SQLException. Creates a prepared SQL statement.
• public PreparedStatement prepareStatement(String sql,
int resultSetType, int concurrency) throws SQLException.
PreparedStatement insert = connection.prepareStatement(
“INSERT INTO Employees VALUES (?, ?, ?, ?)”);
insert.setDouble(2, 2.50);
insert.setInt(1, 103);
insert.setString(3, “George”); Setting the Parameters

int results=insert. executeUpdate();

Executing a Prepared
Statement
Executing a Prepared Statement
• After the values of all the parameters are set, the
prepared statement is executed using one of the
following methods in the PreparedStatement
interface
public ResultSet executeQuery() throws
SQLException.
• Use this method if the SQL statement returns a
resultset, like a SELECT statement.
Cont..
public int executeUpdate() throws SQLException
 Use this method for statements like INSERT,
UPDATE, or DELETE. The return value is the
number of rows affected.
public boolean execute() throws SQLException.
• This method executes any type of SQL statement.
• Use the getResultSet() method to obtain the
result set if one is created.
Scrollable Result Sets
Statement stat = conn.createStatement(type,
concurrency);
• For a prepared statement, use the call
PreparedStatement stat =
conn.prepareStatement( command,type, concurrency );
• The possible values of type are:
TYPE_FORWARD_ONLY The result set is not scrollable.
TYPE_SCROLL_INSENSITIVE The result set is scrollable but not
sensitive to database changes
TYPE_SCROLL_SENSITIVE The result set is scrollable and
sensitive to database changes.
Updatable Result Sets

• If you want to be able to edit resultset data and have the changes
automatically reflected in the database, you need to create an
updatable result set.
• Updatable result sets don't have to be scrollable, but if you present
data to a user for editing, you usually want to allow scrolling as well.

ResultSet concurrency values


CONCUR_READ_ONLY The result set cannot be used to update the database.
CONCUR_UPDATABLE The result set can be used to update the database.

To obtain updatable resultsets, you create a statement as follows.


Statement stat = conn.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE) ;
Then, the result sets returned by a call to executeQuery are
updatable.
Working with ResultSets
• The SQL statements that read data from a database
query return the data in a result set.
• 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.
Cont..
• Methods of the ResultSet interface can be broken
down into three categories:
 Navigational methods used to move the cursor
around.
 Get methods that are used to view the data in the
columns of the current row being pointed to by
the cursor.
 Update methods that update the data in the
columns of the current row.
Navigating a ResultSet:
The cursor is movable based on the properties of the ResultSet.
Some of methods in the ResultSet interface that involve moving
the cursor, including:
• public void beforeFirst() : Moves the cursor to just before the first
row.
• public void afterLast() :Moves the cursor to just after the last row.
• public boolean first() .Moves the cursor to the first row.
• public void last() . Moves the cursor to the last row.
Cont..
• public boolean absolute(int row) . Moves the cursor to the
specified row.
• public boolean relative(int row) Moves the cursor the given
number of rows forward or backwards from where it
currently is pointing.
• public boolean previous() . Moves the cursor to the previous
row. This method returns false if the previous row is off the
result set.
• public boolean next() Moves the cursor to the next row. This
method returns false if there are no more rows in the result
set.
Viewing a ResultSet
The ResultSet interface contains many methods for
getting the data of the current row. There is a get
method for each of the possible data types.
Each get method has two versions:
 that takes in a column name, and column index.
i.e. if the column you are interested in viewing contains an
int, you need to use one of the getInt() methods of ResultSet.
public getInt(String columnName) :Returns the int in the
current row in the column named columnName.
public int getInt(int columnIndex) :Returns the int in the
current row in the specified column index.
Updating a ResultSet
The ResultSet interface contains a collection of update
methods for updating the data of a result set.
 There are two update methods for each data type:
 one that uses the column name and
 one that uses the column index.
i.e. to update a String column of the current row of a result
set, you would use one of the following updateString()
methods:
public void updateString(int columnIndex, String s)
throws SQLException. Changes the String in the specified
column to the value of s.
public void updateString(String colmnName, String s)
throws SQLException. column is specified by its name
instead of its index.
Cont..
• There are update methods for the eight primitive data
types(double, int,float…), as well as String, Object
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
• To update your changes to the row in the
database, you need to invoke the following
method
 Public void updateRow(): Updates the current row by
updating the corresponding row in the database.
Cont..
public void deleteRow():
Deletes the current row from the database
public void refreshRow():Refreshes the data in the
result set to reflect any recent changes in the
database.
public void cancelRowUpdates():Cancels any
updates made on the current row.
public void insertRow():Inserts a row into the
database. This method can only be invoked when the
cursor is pointing to the insert row.
Metadata

• Data that describes the database or one of its parts is called


metadata.
• To find out more about the database, you need to request an
object of type DatabaseMetaData
DatabaseMetaData meta = conn.getMetaData();
• The DatabaseMetaData class gives data about the
database.
• ResultSetMetaData, that reports information about a result
set. Whenever you have a result set from a query, you can
inquire about the number of columns and each column's
name, type, and field width.
Cont..
i.e. ResultSet rs = stat.executeQuery("SELECT * FROM "
+ tableName);
ResultSetMetaData meta = rs.getMetaData();
for (int i = 1; i <= meta.getColumnCount(); i++)
{
String columnName = meta.getColumnLabel(i);
int columnWidth = meta.getColumnDisplaySize(i);
Label l = new Label(columnName);
TextField tf = new TextField(columnWidth);
}
CallableStatement Interface
• To call the stored procedures and functions,
CallableStatement interface is used.
• We have a business logic on the database by the use of
stored procedures and functions that will make the
performance better because these are precompiled.
• The prepareCall() method of Connection interface returns
the instance of CallableStatement.
Syntax public CallableStatement prepareCall(“
{ call procedurename(?,?...?)}");
i.e. CallableStatement stmt=con.prepareCall(
"{call myprocedure(?,?)}");
• It calls the procedure myprocedure that receives 2
arguments.
Stored Procedure
DELIMITER $$
DROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $
$
CREATE PROCEDURE `EMP`.`getEmpName`
(IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END $$
DELIMITER ;
Cont..
Three types of parameters exist: IN, OUT, and INOUT.
 The PreparedStatement object only uses the IN
parameter.
 The CallableStatement object can use all three.

Parameter Description

A parameter whose value is unknown when the SQL statement is created.


IN
You bind values to IN parameters with the setXXX() methods.
A parameter whose value is supplied by the SQL statement it returns.
OUT You retrieve values from theOUT parameters with the getXXX()
methods.
A parameter that provides both input and output values. You bind
INOUT variables with the setXXX() methods and retrieve values with the
getXXX() methods.
Cont..
• When you use OUT and INOUT parameters you must
employ an additional CallableStatement method,
registerOutParameter().
• The registerOutParameter() method binds the JDBC data
type to the data type the stored procedure is expected to
return.
• you retrieve the value from the OUT parameter with the
appropriate getXXX() method. This method casts the
retrieved value of SQL type to a Java data type.
Example
import java.sql.*;
public class Proc {
public static void main(String[] args) throws Exception{
Class.forName(" com.mysql.jdbc.Driver ");
Connection con=DriverManager .getConnection
(“jdbc:mysql://localhost/databaseName“,user,pw);
CallableStatement stmt=con.prepareCall("{call insertR(?,?)}
");stmt.setInt(1,1011);
stmt.setString(2,"Amit");
stmt.execute();
System.out.println("success");
} }
Transaction Processing
• Transaction processing enables a program that
interacts with a database to treat a database
operation (or set of operations) as a single operation.
Such an operation also is known as an atomic
operation or a transaction.
• At the end of a transaction, a decision can be made
either to commit the transaction or roll back.
• Committing the transaction finalizes the database
operation(s); the transaction cannot be reversed
• Rolling back the transaction leaves the database in
its state prior to the database operation.
Cont..
• Methods of interface Connection
• setAutoCommit specifies whether each SQL
statement commits after it completes (a true
argument) or if several SQL statements should be
grouped as a transaction (a false argument)
• If the argument to setAutoCommit is false, the
program must follow the last SQL statement in
the transaction with a call to Connection
method commit or rollback
• getAutoCommit determines the autocommit state
for the Connection.
Example
1. import java.sql.*;
2. class FetchRecords{
3. public static void main(String args[])throws Exception{
4. Class.forName(" com.mysql.jdbc.Driver ");
5. Connection con=DriverManager.getConnection
(“jdbc:mysql://localhost/databaseName“,user,pw);
6. con.setAutoCommit(false);
7. Statement stmt=con.createStatement();
9. stmt.executeUpdate("insert into user420 values
(190,'abhi',40000)");
10 stmt.executeUpdate("insert into user420 values
(191,'umesh',50000)");
12. con.commit();
13. con.close();
end
Thank you!!!

You might also like