Vous êtes sur la page 1sur 31

JDBC

Java Database
Connectivity

What is JDBC Driver ?


JDBC drivers are set of API or software for
letting a java program interact with the
database system.
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.
TheJava.sqlpackage that ships with JDK
contains various classes with their behaviours
defined and their actual implementaions are
done in third-party drivers.

Driver Types

Type
Type
Type
Type

1:
2:
3:
4:

JDBC-ODBC Bridge Driver


JDBC-Native API
JDBC-Net pure Java
100% pure Java

Type 1: JDBC-ODBC Bridge Driver

In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed


on each client machine. TranslatesJDBCAPIcalls into Microsoft Open
Database Connectivity (ODBC)calls that are then passed to
theODBCdriver. The ODBC driver then calls d vendor specific driver.
Disadvantages 1) Performance overhead because of extra ODBC layer 2)
Client code has to be installed on each machine
Ex. JDBC-ODBC bridge that comes with JDK 1.2

Type 2: JDBC-Native API

In a Type 2 driver, JDBC API calls are converted into native C/C++
API calls which are unique to the database. These drivers typically
provided by the database vendors and used in the same manner
as the JDBC-ODBC Bridge, the vendor-specific driver must be
installed on each client machine.
The native API as it is specific to a database so still it had to be
installedon each machine
some speed increase with a Type 2 driver, because it eliminates
ODBC's overhead.
Ex. OCI

Type 3: JDBC-Net pure Java

Three-tier approach - The JDBC clients use standard network sockets to


communicate with an middleware application server. The socket
information is then translated by the middleware application server into
the call format required by the DBMS, and forwarded to the database
server.
This kind of driver is extremely flexible, since it requires no code installed
on the client and a single driver can actually provide access to multiple
databases.
JDBC "proxy," meaning that it makes calls for the client application.

Type 4: 100% pure Java

In a Type 4 driver, a pure Java-based driver that communicates directly


with vendor's database through socket connection. highest performance,
usually provided by the vendor itself.
This kind of driver is extremely flexible, you don't need to install special
software on the client or server. Further, these drivers can be downloaded
dynamically.
MySQL's Connector/J driver is a Type 4 driver.

Steps involved in interacting with


DBMS
1.
2.
3.
4.
5.

Import JDBC package


Load and Register JDBC Driver
Create a connection to database
Create a statement to execute queries
Execute the statement object and return a
query Resultset.
6. Process the Resultset.
7. Close the connection, Resultset and
statement
objects.

Import JDBC package


Import java.sql package All the
classes and interfaces required for
JDBC are available in this package.
So in order for these classes to be
available you should import these
into your class.
Import java.sql.*;

Loading and Registering the


Drivers
You must register the your driver in your
program before you use it. Registering the
driver is the process by which the Oracle
driver's class file is loaded into memory so it
can be utilized using JDBC interfaces. We have
to inform DriverManager about the required
driver and this is done with the help of
Type 1
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Type 4
Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("com.mysql.jdbc.Driver);

Connection to the DB
After you've loaded the driver, you can establish a
connection using the
DriverManager.getConnection()method. The three
overloaded DriverManager.getConnection() methods:
getConnection(String url)
getConnection(String url, Properties prop)
getConnection(String url, String user, String password)
Here each form requires a databaseURL. A database URL
is an address that points to your database.
Formulating a database URL is where most of the
problems associated with establishing a connection occur.

Database URL formation Type 1


RDBMS

JDBC driver name

URL

Any
Database

sun.jdbc.odbc.JdbcOdbcD jdbc:odbc:ODBC Driver Name


river

Database URL formation


Type 4

RDBMS

JDBC driver name

URL format

MySQL

com.mysql.jdbc.Driver

jdbc:mysql://hostname/
databaseName

ORACLE

oracle.jdbc.driver.OracleDriv jdbc:oracle:thin:@hostname:p
er
ort Number:databaseName

DB2

COM.ibm.db2.jdbc.net.DB2D jdbc:db2:hostname:port
river
Number/databaseName

Sybase

com.sybase.jdbc.SybDriver

jdbc:sybase:Tds:hostname:
port Number/databaseName

Creating Connection Object


If you have a host at TCP/IP address 192.0.0.1 with a host
name of myhost, and your Oracle listener is configured to
listen on port 1521, and your database name is EMP, then
complete database URL would then be:
Type 1 URL would be
jdbc:odbc:ODBCDriverName

Type 4 URL would be


jdbc:mysql://myhost/EMP

Now you have to call getConnection() method with


appropriate username and password to get
Connectionobject as follows:
String URL = "jdbc:mysql://myhost/EMP";
String USER = "username"; String PASS = "password;
Connection conn = DriverManager.getConnection(URL, USER, PASS);

Create a statement to execute queries


A statement object is used for executing a static SQL
statement and obtaining the results produced by it.
There are three types of statements in Java.
Statement - Use for general-purpose access to your
database. Useful when you are using static SQL
statements at runtime.
createStatement() Returns a new statement object.

PreparedStatement - Use when you plan to use


the SQL statements many times with different
values. prepareStatement(String SQL) Returns a
PreparedStatetment object.

CallableStatement Used for object for calling


stored procedures.
prepareCall(String sql) Returns a new CallableStatement

Execute the statement object


and return a query resultset.
The SQL statements that read data from a database
query return the data in a result set. The SELECT
statement is the standard way to select rows from a
database and view them in a result set. The
java.sql.ResultSetinterface represents the result set
of a database query.
Three ways to execute query is
ResultSet executeQuery(String) Used to execute select
kind of queries
Int executeUpdate(String) Used to execute Insert, Update,
Delete like DML statements
Boolean execute(String) Used to execute statement that
may return multiple results.

Process the ResultSet.


A ResultSet provides access to a table of data
generated by executing a Statement. Only one
ResultSet per statement can be opened at
once. The table rows are retrieved in sequence.
A ResultSet maintains a pointer to its current
row of data. The next method moves the cursor
to the next row. Five IMP methods used while
retrieving data from resultset

Boolean First()
Boolean Last()
Boolean Next()
Type getType(int columnIndex)
Type getType(String ColumnName)

Close the connection, resultset


and statement objects
After you have used the connection,
resultset and statement objects, it is
always advisable to close them
before ending the program otherwise
they will be floating unnecessary in
memory and preventing further
connections.
con.close();
stmt.close();
rs.close();

Simple JDBC program


import java.sql.*;
class SimpleJDBCProgram{
public static void main(String args[]){
Connection con=null;
Statement stmt=null;
String query;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:NishaMysql10");
stmt = con.createStatement();
query = "select * from student";
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
System.out.print(rs.getString(1)+"\t");
System.out.print(rs.getString(2)+"\t");
System.out.print(rs.getString(3)+"\t");
System.out.println(rs.getString(4)+"\n");
}
stmt.close();
con.close();
}
catch(SQLException e){
}catch(Exception e){
}
}
}

Example of PreparedStatement
import java.sql.*;
public class jdbcConn {
public static void main(String[] args)
throws Except{
int id = 23;
String name = Roshan;
String desg = CEO;
Class.forName("
sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection
(" jdbc:odbc:NishaMysql10
","name,pass");
PreparedStatement pstmt
=con.prepareStatement
("insert into emp values(?,?,?)");
pstmt setInt(1,id);
pstmt.setString(2,name);
pstmt setString(3, desg);

Statement stmt = con.


prepareStatement("select * from
emp
where id=?);
stmt. setInt(1,id);
ResultSet rs =
stmt.executeQuery();
System.out.println("Id Name
Job");
while (rs.next()) {
int id = rs.getInt("id");
String name =
rs.getString("name");
String job =
rs.getString("job");
System.out.println(id + " " +
name+" "+job);
}
}
}

Example of Callable
Statement
import java.sql.*;
//Bind IN parameter first, then bind
public class JDBCExample {
static final String JDBC_DRIVER = "
sun.jdbc.odbc.JdbcOdbcDriver";
static final String DB_URL = "
jdbc:odbc:NishaMysql10";
static final String USER =
"username";
static final String PASS = "password";
public static void main(String[] args)
{
Connection conn = null;
CallableStatement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driv
er");
conn = DriverManager.
getConnection(DB_URL,USER,PAS
S);

OUT parameter
int empID = 102;
stmt.setInt(1, empID); // This
would set ID as 102, Because second
parameter is OUT so register it
stmt.registerOutParameter(2,
java.sql.Types.VARCHAR);
//Use execute method to run stored
proc
stmt.execute();
//Retrieve employee name with
getXXX meth
String empName =
stmt.getString(2);
System.out.println("Emp Name
with ID:" +
empID + " is " +
empName);
stmt.close();

Example of Swing and JDBC


import java.sql.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class SelectSwingJDBC extends JFrame implements ActionListener{
JLabel l1;
JTextField t1;
JTextArea ta;
JButton b1;
Connection conn;
Statement stmt;
ResultSet rs;
public SelectSwingJDBC(){
setLayout(new FlowLayout());
l1= new JLabel("Enter Roll No");
t1= new JTextField(20);
ta= new JTextArea(5,30);
b1= new JButton("Submit");
add(l1);
add(t1);
add(ta);
add(b1);
b1.addActionListener(this);
setSize(400,200);
createConnection();
}

public void actionPerformed(ActionEvent ae){


try{
int rollNo = Integer.parseInt(t1.getText());
String s="";
String query = "select * from student where rollno = "+rollNo;
rs = stmt.executeQuery(query);
while(rs.next())
{
s=s+rs.getString(1)+"\t"+
rs.getString(2)+"\t"+
rs.getString(3)+"\t"+
rs.getString(4)+"\n";
}
if(s.equals("")){
JOptionPane.showMessageDialog(this, "No Record Found");
}else{
ta.setText(s);
}
}catch(Exception e){
JOptionPane.showMessageDialog(this, e.getMessage());
}
}
public void createConnection(){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:college");
stmt=conn.createStatement();
}catch(Exception e){
JOptionPane.showMessageDialog(this, e.getMessage());
}
}
public static void main(String args[]){
SelectSwingJDBC ssj = new SelectSwingJDBC ();
ssj.setTitle("Select data");
ssj.setVisible(true);
ssj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Scrollable and Updatable


Resultset
By default resultsets are not scrollable, you can move over them only
in one direction using next() method. To obtain scrollable result sets
from statements you need to prepare the statements differently by
specifying more parameters.
Statement stmt = con.createStatement(type, concurrency);
PreparedStatement pstmt = con.createStatemet(type, concurrency);
ResultSet type values:
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.
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.

Methods to use Scrolling and


Updatable feature
if (rs.p reviou s()) . . .
to scroll backward. The method returns true if the cursor is positioned
on an actual row; false if it now is positioned before the first row.
You can move the cursor backward or forward by a number of rows
with the command
rs.relative(n);
If n is positive, the cursor moves forward. If n is negative, it moves
backwards. If n is zero, the call has no effect. If you attempt to move
the cursor outside the current set of rows, then, the method returns
false and the cursor does not move. The method returns true if the
cursor landed on an actual row.
Alternatively, you can set the cursor to a particular row number:
rs.ab solu te(n);
You get the current row number with the call
in t n = rs.g etR ow ();
The first row in the result set has number 1. If the return value is 0,
the cursor is not currently on a rowit is either before the first or
after the last row.

String query = "SELECT * FROM Books";


ResultSet rs = stat.executeQuery(query);
while (rs.next()) {
if (. . .){
double increase = . . .
double price = rs.getDouble("Price");
rs.updateDouble("Price", price + increase);
rs.updateRow();
}
}
There are updateXxx methods for all data types
that correspond to SQL types, such as
updateDouble, updateString, and so on. As with
the getXxx methods, you specify the name or the
number of the column. Then, you specify the new
value for the field.

The u p d ateXxx method only changes the row


values, not the database. When you are done with the
field updates in a row, you must call the u p d ateR ow
method. That method sends all updates in the current
row to the database.
If you move the cursor to another row without calling
u p d ateR ow , all updates are discarded from the row
set and they are never communicated to the
database. You can also call the can celR ow U p d ates
method to cancel the updates to the current row.
If you want to add a new row to the database, you
first use the m oveToIn sertR ow method to move the
cursor to a special position, called the in sertR ow .
You build up a new row in the insert row position by
issuing u p d ateX xx instructions. Finally, when you are
done, call the in sertR ow method to deliver the new
row to the database. When you are done inserting,
call m oveToC u rren tR ow to move the cursor back to
the position before the call to m oveToIn sertR ow .

rs.moveToInsertRow();
rs.updateString("Title", title);
rs.updateString("ISBN", isbn);
rs.updateDouble("Price", price);
rs.insertRow();
rs.moveToCurrentRow();
Finally, you can delete the row under the cursor.
rs.deleteRow();
The deleteRow method immediately removes the row
from both the result set and the database.
The updateRow, insertRow, and deleteRow
methods of the ResultSet class give you the same
power as executing UPDATE, INSERT, and DELETE
SQL commands. However, programmers who are used
to the Java programming language will find it more
natural to manipulate the database contents through
result sets than by constructing SQL statements.

Ex. of scrollable and updateable resultset


Import java.sql.*
Public class void main(String args[]){
Connection con;
Statement stmt;
try{
Class.forName(com.mysql.jdbc.Driver);
con= DriverManager.getConnection(jdbc:mysql://localhost/EMP);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.execute(select * from student);
rs.absolute(1);
rs.updateString(2,Sachin);
rs.updateRow();
stmt.close();
Con.close();
rs.close();
catch(Exception e){
e.printStackTrace();
}
}
}

Metadata
D atab aseM etad ata - JDBC can give you additional
information about the structure of a database and its
tables. For example, you can get a list of the tables
in a particular database or the column names and
types of a table.
DatabaseMetaData meta = conn.getMetaData();
ResultSet rs = meta.getTables(null, null, null, new String[]
{ "TABLE" });

R esu ltS etM etaD ata - gives you the metadata


associated with the current ResultSet columns.
int getColumnCount()
int getColumnDisplaySize(int column)
String getColumnLabel(int column)
String getColumnName(int column)

Transaction
The major reason for grouping commands into
transactions is database integrity. For example,
suppose we want to add a new book to our book
database. Then, it is important that we simultaneously
update the Books, Authors, and BooksAuthors table. If
the update were to add new rows into the first two
tables but not into the third, then the books and
authors would not be properly matched up.
If you group updates to a transaction, then the
transaction either succeeds in its entirety and it can be
committed, or it fails somewhere in the middle. In that
case, you can carry out a rollback and the database
automatically undoes the effect of all updates that
occurred since the last committed transaction.
By default, a database connection is in autocommit
mode, and each SQL command is committed to the
database as soon as it is executed. Once a command is
committed, you cannot roll it back.

Transaction
You can group a set of statements to form a transaction. Thetransaction can be committed when
all hasgone well. Ot if an error occurred in one of them, it can be rolled back as if none of them has
been issued. The major reason for grouping statements into transaction is database intigrity.
By default a database connection is in autocommit mode, and each SQL statement is committed to
the database as soon as it is executed. Once a statement is committed you cant roll it back. Turn
off this default when you use transaction;
Con.setAutoCommit(false);
Create a statement in a normal way
stmt = con.createStatement();
Call executeUpdate() or Insert or delete
Stmt.executeUpdate(command1);
Stmt.executeUpdate(command2);
Stmt.executeUpdate(command3);
Stmt.executeUpdate(command4);
If statements have been excuted successfully call
Con.commit()
Else if an error occure in the exception block use
Con.rollback();
The all the statements until the last commit are automatically reserved. You generally isssue a
rollback statement when your transaction was interrupted by SQLException

Vous aimerez peut-être aussi