Java Database Connectivity
Download
Report
Transcript Java Database Connectivity
Java Database Connectivity
Java and the database
• Database is used to store data. It is also known
as persistent storage as the data is stored and
can be retrieved anytime.
• Java and database are used almost
everywhere to store persistent data and
retrieve it when required.
SQL
• Information stored in the database is in tables
and the language used to query information
from the database is SQL.
• Using SQL we can query a table based on the
requirement.
CRUD OPERATIONS
• CRUD stands for create, read, update, delete.
• Create statement in SQL looks like
– Create table mytab ( mynum number , name
varchar2(25));
• READ statement looks like
– Select * from mytab where mynum=25;
• UPDATE statement looks as
– Update mytab set mynum=88 where mynum=25;
• DELETE statement like
– Delete from mytab where mynum=88;
DDL – DML – DCL - TCL
• DDL – Data Definition Language
– These queries are used to create database objects such as
tables, indexes, procedures, constraints
– Create , drop, alter,truncate,comment,rename
• DML – Data Manipulation Language
– These queries are used to manipulate the data in the database
tables.
– Insert, update, delete, select (more available)
• DCL – Data Control Language
– These are data control queries like grant and revoke permissions
• TCL– Transaction Control Language
– These are transaction control queries like commit, revoke,
savepoint, set transaction
CRUD and Java
• Java can invoke CRUD operations using JDBC
• JDBC is Java Database Connectivity and there
are 4 types of drivers which form a bridge
between java and a database
• The Operations communicated by java will be
translated in a form understood by the
database by the drivers.
JDBC Drivers
• Type 1 Driver - JDBC-ODBC bridge
– This is an ODBC driver, which is open source
• Type 2 Driver – Native API driver
– This is more like the OCI (Oracle Call Interface) call
interface is converted to native calls of the database.
• Type 3 Driver – Network protocol driver
– This is achieved by using a Java Driver in a middleware
• Type 4 Driver – Native Protocol Driver
– This is a driver written purely in Java Language
• We Usually prefer to depend on the Type 4 driver
– Eg: Oracle thin driver
Java-Oracle Example
public void ConnectToAndQueryDatabase
(String username, String password)
{
Connection con =
DriverManager.getConnection(
"jdbc:myDriver:myDatabase", username,
password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT
a, b, c FROM Table1");
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}
}
•In the example
•We have a method call
ConnectToAndQueryDatabase which
takes in a username, password
•The Connection Interface creates a
connection. A connection is created by
using the DriverManager Class with the
connection string , username, password.
The concrete implementation is
OracleConnection.
•The statement Interface creates a
statement. The concrete implementation
is Oracle Statement.
•ResultSet stores the result after invoking
execute Query on the statement object.
We can iterate over the resultset to get
the results from table.
Statement and Prepared Statement
• A Statement Interface is used to create a statement i.e.
a query to be executed against a database. In this
process, two calls are made to the database system ,
one to get the table metadata and other to get the
data itself. The statement object is also compiled every
time it executes.
• A Prepared statement comes in handy as it is compiled
and cached and only makes on database call when
invoked. The compilation would be skipped even if the
values in the where clause change
Statement and Prepared Statement
• Statement
Statement stmt= con.statment(“select * from mytab where num=22”);
• Prepared Statement
PreparedStatement pstmt = con.preparestatement(select * from mytab where num=?”);
pstmt.setInt(1,”11”);
This sets the value of ? as 11
– If we run the statement in for loop every time
changing the where clause, the statement is
compiled every time before execution.
– In the case of prepared statement , the prepared
statement is cached and compiled only one time in
the event of a for loop with changing where clause.
Stored Procedures
• Stored procedures are compiled sql programs
which are stored in the database system and
can be executed in the database.
• We use the call keyword in SQL to execute
stored procedures
• Java can access the stored procedures in the
database by using the Callable statements
Callable Statements
• Callable statements are used to call stored
procedures in the database.
CallableStatement cstmt = null;
try {
String SQL = "{call myprocedure(?, ?)}"; //? Can be set dynamically as in
prepared statement
cstmt = conn.prepareCall (SQL);
...
}
catch (SQLException e) {
...
}
finally {
...
}
Transactions
• Transactions imply a situation when we have one
or more SQL statements to be committed only
when everything goes right
– Assume we have 10 databases which are always to be
in sync. So we would have one sql query to be
executed across all databases. So, the sql query should
committed in all the databases only after successful
execution in all 10 databases. This is called a
transaction. The transaction is committed only after
successful execution across all databases.
Closing Connections
• Always remember to close in the following
sequence.
– Resultset
– Statement/Prepared Statement
– Connections
• Do a null check always before closing the
connections using close() method.