Vous êtes sur la page 1sur 8

Java Data Base Connectivity

JDBC is a mediator between the Java Application and the database. It is Similar to
Open Data Base Connectivity on Win32 but still JDBC is much simpler to use and
more robust.
JDBC 1.2: version for the JDK 1.1 it is Based on SQL2
JDBC 2.0: version for Java2 Supports SQL3 and Data Types, it Allows the
recovery and modification of data
JDBC source code is independent of the database, the application communicates with
supported databases using JDBC translator which translate the standard actions in to
specific actions (Oracle, Sybase...)

ODBC - Open Database Connectivity:


This is a standard application-programming interface (API) for accessing
database like SQL Access Group, chiefly, Microsoft. By using ODBC statements in a
program, you can access files in a number of different databases including Access,
Excel and Text files.
The text file is a comma separated file format, which is read directly as a
database file. The database access is based on the Open Group standard SQL Call-
Level Interface
It allows programs to use SQL requests that will access databases without
having to know the proprietary interfaces to the databases. ODBC handles the SQL
request and converts it into a request, which the individual database system
understand.

How to work with JDBC:


1. Import Packages for gaining the interface.
import java.sql.*;
2. Register the JDBC Drivers –indicating the database driver we want to use and
Open a Connection to a Database (opening the file).
// Using the SUN driver handler object.
Connection cxt = DriverManager.getConnection ("jdbc:odbc:client", "user", "1234");
3. Create Statement Object - object for handling the driver connectivity.
// Creating the query object handler.
Statement stmt = cxt.createStatement();
4. Execute Query and Return a Result Set Object
// Create a response handler object.
ResultSet rs = stmt.executeQuery("SELECT user, amount FROM Invoice ");
while (rs.next()) { // as long as there is data to read.
String invoiceId = rs.getString("user");
float amount = rs.getFloat("amount");
}
5. Process the Result Set.
6. Close the Result Set and Statement Objects – for releasing resources.
7. Close the Connection

JDBC main classes: Statement


executeQuery(String)
Connection executeUpdate(String)
createStatement() execute(String)
prepareStatement(String) getMoreResults()
prepareCall(String) getResultSet()
getMetaData() getUpdateCount()

ResultSet
getInt(int)
getInt(String)
DriverManager getString(int)
getConnection getString(String)
PreparedStatement
executeQuery()
executeUpdate()
execute()
setInt(int, int)
setString(int, String)

CallableStateme
getInt(int)
getString(int)
Data Source and Driver:
Data source is the Data Base created using any of the common database
applications available. Your system should have the driver for the database you will
be using. For example your Windows system should have the MS Access Driver.
There are a number of JDBC drivers available. Information on installing them is
available at: http://industry.java.sun.com/products/jdbc/drivers

Driver Manager:
The class DriverManager allows to: obtain the list of available database
drivers, open a database, Connection Object. There is no way to request list of
installed drivers except for trying out each driver we know.
DriverManager matches connection requests from the java application with
the proper database driver using communication subprotocol. The first driver that
recognizes a certain sub-protocol under jdbc (such as odbc) will be used to establish a
database Connection.
For local host (data base on the application computer):
Connection c = DriverManager.getConnection(String url, String user, String passwd)
Connection c = DriverManager.getConnection(String url, Properties info)
- url = jdbc:subprotocol:subname (jdbc:odbc:client)
- Identification: user, password or list of name/value pairs
Use the class DatabaseMetaData to get information about the database schema.

Application
Application in
in Java
Java
PPII PII
b ccAA rddAAP
jddb ar
Application in j tanndda
Application in DriverManager
DriverManager
Java ss ta
Java bcc
ooddb

Sybase
Sybase driver
driver mSQL
mSQLdriver
driver Access
Access driver
driver

Rina
RinaZviel-Girshin
Zviel-Girshin @ARC
@ARC 11
11
The Statement class
Interface created by Connection.createStatement() Can be executed by:
ResultSet executeQuery(String sql) - used for consultation SELECT.
if updating is used it is not executed and an exception is thrown.
Int executeUpdate(String sql) - used for modification UPDATE, DELETE, INSERT
Boolean execute(String sql) - to be used when you do not know the type of the
request result. Updating is allowed.
Statement stmt = cxt.createStatement();
Example :
ResultSet rs = stmt.executeQuery("SELECT user, amount FROM Invoice");

Statement.executeQuery:
SQL query return a ResultSet use with SELECT command. The result is
recovered in a ResultSet - The result of an SQL request is a matrix of values allows
the retrieving of values for each resulting row
Example:
Statement stmt = cxt.createStatement();
ResultSet rs = stmt.executeQuery("SELECT user, amount FROM Invoice ");
while (rs.next()) {
String invoiceId = rs.getString("user");
float amount = rs.getFloat("amount");
}
Statement.executeUpdate:
• SQL command returning no ResultSet
• Returns the number of rows changed
• Used for the following SQL commands:
– INSERT: add a row in a table
– UPDATE: modify a row in a table
– DELETE: destroy a row in a table
• An SQL command is taken as parameter for Statement
• No parameter for PreparedStatement or for CallableStatement
Example:
// Question mark ‘?’ is a primitive character which indicates an unknown
// string. The string is indexed automatically by the “setString” method.
String sql = "INSERT INTO Client (clientId, corporateName, address, town,
postCode) " + " VALUES (?,?,?,?,?)";
PreparedStatement stmt = cxt.prepareStatement(sql);
while(true)
{
String clientId, corporateName, address, town, postCode;
//... Read the keyboard data...
stmt.setString(1, clientId);
stmt.setString(2, corporateName);
stmt.setString(3, address);
stmt.setString(4, town);
stmt.setString(5, postCode);
int result = stmt.executeUpdate();
System.out.println("result = " + result); // returns 1
}
Transaction
Set of executed SQL commands (SQL queries) on a database. If one query is
wrong the transaction is cancelled. The set of commands are can check the data and
execute update while verifying the result arrives at the transaction caller.
Transaction control:
* A transaction can be validated: Connection.commit()
* A transaction can be cancelled: Connection.rollback()
* Assure the integrity of data on multiple SQL commands. By default,
JDBC uses the “auto-commit” mode. This mode is deactivated for
transactional access Connection.setAutoCommit(boolean)
You can also control the isolation level.
Example:
// For avoiding update on the database source first cancel the AutoCommit.
cxt.setAutoCommit(false);
try {
stmt.executeUpdate("UPDATE ..."); // not update yet.
stmt.executeUpdate("UPDATE ..."); // not update yet.
stmt.executeUpdate("UPDATE ..."); // not update yet.
cxt.commit(); // Update the database file.
}
catch(Exception e)
{ cxt.rollback(); }

The ResultSet class


• Contains the result of an SQL command (SELECT)
– Contains a table of values
• Has a current position on a row: the cursor
– The cursor is moved by ResultSet.next()
– Returns true if there are rows still needing to be read; false if not
• To recover the value of a column of the current row:
– Operations realizing the conversion of SQL/Java types
– XXX getXXX(int pos): pos = column (starts at 1)
– XXX getXXX(String name): name = column name
ResultSet rs = stmt.executeQuery("SELECT user, amount FROM Invoice ");
while (rs.next()) {
String invoiceId = rs.getString("user");
float amount = rs.getFloat("amount");
}
More ResultSet methods:
For every SQL type there is the equivalent java method. For the user types we
retrive as text and buld the get conversion function.
rs.getFloat(String/int s), .getInt(String/int s), .getString(String/int s),
.getDate(String/int s), .getTimestamp(String/int s)
rs.next(), .previous(), .last(), .relative(int num)
rs.getMetaData() // information about the type of data day type/currency type…
XML database has a different access package.

Example –table creation:


import java.sql.*;
public class CreateCoffees
{
public static void main(String args[]) {
String url ="jdbc:mySubprotocol:myDataSource";
Connection con;
String createString;
createString = "create table COFFEES (COF_NAME varchar(32), " +
"SUP_ID int, PRICE float, SALES int, TOTAL int)";
Statement stmt;
try {
con = DriverManager.getConnection(url,"myLogin", "myPassword");
stmt = con.createStatement();
stmt.executeUpdate(createString);
stmt.close();
con.close();
}
catch(SQLException ex)
{ System.err.println("SQLException: " + ex.getMessage());}
}
}//end of class
XML