Vous êtes sur la page 1sur 94

JAVA DATABASE CONNECTIVITY (JDBC)

Prepared By: Ishita N.Theba, C.E. Dept, A.D.I.T

Agenda
Overview of JDBC JDBC Drivers Seven Basic steps in using JDBC Retrieving data from ResultSet Using prepared statement and callable statement

JDBC (Java DB Connectivity)


Java application { ... "SELECT ... FROM ... WHERE" ... }

DBMS

JDBC Architecture Two-tier and Three-tier Processing Models The JDBC API supports both two-tier and three-tier processing models for database access.

Figure 1: Two-tier Architecture for Data Access

In the two-tier model, a Java applet or application talks directly to the data source. This requires a JDBC driver that can communicate with the particular data source being accessed. A user's commands are delivered to the database or other data source, and the results of those statements are sent back to the user. The data source may be located on another machine to which the user is connected via a network. This is referred to as a client/server configuration, with the user's machine as the client, and the machine housing the data source as the server. The network can be an intranet, which, for example, connects employees within a corporation, or it can be the Internet.

Figure 2: Three-tier Architecture for Data Access

In the three-tier model, commands are sent to a "middle tier" of services, which then sends the commands to the data source. The data source processes the commands and sends the results back to the middle tier, which then sends them to the user. MIS directors find the three-tier model very attractive because the middle tier makes it possible to maintain control over access and the kinds of updates that can be made to corporate data. Another advantage is that it simplifies the deployment of applications. Finally, in many cases, the three-tier architecture can provide performance advantages.

Until recently, the middle tier has often been written in languages such as C or C++, which offer fast performance. However, with the introduction of optimizing compilers that translate Java bytecode into efficient machine-specific code and technologies such as Enterprise JavaBeans, the Java platform is fast becoming the standard platform for middle-tier development. This is a big plus, making it possible to take advantage of Java's robustness, multithreading, and security features.

With enterprises increasingly using the Java programming language for writing server code, the JDBC API is being used more and more in the middle tier of a three-tier architecture. Some of the features that make JDBC a server technology are its support for connection pooling, distributed transactions, and disconnected rowsets. The JDBC API is also what allows access to a data source from a Java middle tier.

JDBC Drivers
A driver is a java class, usually supplied by the database vendor, which implements the java.sql.Driver interface. The primary function of driver is to connect to a database and return a java.sql.connection object.

Driver arent called directly by application programs. Instead they are registered with the DriverManager, which determines the appropriate driver for a particular connection request and makes connection.

JDBC Drivers
Java application
JDBCDriver manager Native Protocol driver JDBCNet-driver DBMiddleware JDBC-ODBC bridge ODBC Client library Native API-driver Client library

JDBC-API

Type-4

Type-3

Type-2 Type1

Driver Types
According to their architecture, they can be divided into 4 types: 1) Type 1: Drivers that implement the JDBC API as a mapping to another data access API, such as ODBC (Open Database Connectivity). Drivers of this type are generally dependent on a native library, which limits their portability. The JDBC-ODBC Bridge is an example of a Type 1 driver.

2) Type 2: Drivers that are written partly in the Java programming language and partly in native code. These drivers use a native client library specific to the data source to which they connect. Again, because of the native code, their portability is limited. Oracle's OCI (Oracle Call Interface) client-side driver is an example of a Type 2 driver

3) Type 3: Drivers that use a pure Java client and communicate with a middleware server using a databaseindependent protocol. The middleware server then communicates the client's requests to the data source.

4) Type 4: Drivers that are pure Java and implement the network protocol for a specific data source. The client connects directly to the data source.

Seven Steps
Load the driver
Define the connection URL Establish the connection Create a Statement object Execute a query using the Statement

Process the result


Close the connection

Running a JDBC Application


Phase Task Relevant java.sql classes

Initialisation

Load driver Create connection

DriverManager Connection

Processing

Generate SQL statements Process result data

Statement ResultSet etc.

Termination

Terminate connection Release data structures

Connection Statement etc.

Essential JDBC Classes


JDBC is contained in java.sql and javax.sql packages. 1) Connection :
An active link to a database through which a java program can read and write data, as well as explore the database structures and capabilities. A connection object is created by a call to either DriverManager.getConnection() or DataSource.getConnection().

2) Statement :
A JDBC statement object is used to send your SQL statement to the database server A JDBC statement is associated with an open connection and not any single SQL statement JDBC provides three classes of SQL statement Statement PreparedStatement CallableStatement

(i) Statement: It is used to execute static SQL strings created with Connection.CreateStatement() (ii) Prepared Statement: An extension of statement that uses precompiled SQL, possibly with dynamically set i/p parameters created with Connection.PreparedStatement(SQL);

(iii) Callable statement:


It invokes a stored procedure. Once a statement is created, it can be used to execute commands. Four methods exists for doing this: (a) executeQuery(): It is used to execute an SQL select statement and to return a result set.

(b) executeUpdate()
It is used with the SQL insert, update or delete statements or with data defination statements such as create table. It returns a count of the number of rows updated or deleted.

(c) execute(): It can be used for either purpose but is intended for those statements that return either an update count, multiple result sets or some combination. It returns a boolean flag that indicates whether its result was an update count or a result set.

(d) executeBatch(): allows multiple update statements to be executed in a batch. The update counts are returned in an array.

3) ResultSet: An ordered set of table rows produced by an SQL query. A Resultset is most often encountered as the return value of a statement.executeQuery(Sql query); method call.

4) DriverManager: A class that registers JDBC drivers and supplies connection that can handle specific JDBC urls. The only method commonly used is the static DriverManager.getConnection() which returns an active connection object bound to specified JDBC url.

5) SQLException: The base exception class used by the JDBC API.

Detailed description of all steps in JDBC


Load the driver for DBMS
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Establish the connection


Use driver to open a connection to a particular database. This is done with a call to a static getConnection(url) method to the DriverManager class. The url arg is in a specific form that indicates driver type and the dataSource to use.

For establishing connection to db, we use:


Connection conn; conn = DriverManager.getConnection("jdbc:odbc:myds n1");

Create a Statement object


Once connection is established, it can be used to create statement object through which SQL commands can be made. We use:
Statement stmt; stmt=conn.createStatement();

Execute a query using the Statement :


Statement stmt; ResultSet rs;

rs = stmt.executeQuery(Select * from tablename);

Process the result The ResultSet interface provides methods to step through each row and get the values of each column.
eg: while(rs.next()) { name= rs.getString(name)); }

Close the connection


eg: rs.close(); stmt.close(); conn.close();

A Simple JDBC application


loadDriver getConnection createStatement execute(SQL) Result handling

yes
More results ? no closeStatment closeConnection

import java.sql.*; public class jdbctest { public static void main(String args[]){ try{ Class.forName("org.postgresql.Driver"); Connection con = DriverManager.getConnection ("jdbc:postgresql://lsir-cis-pc8:5401/pcmdb", "user", "passwd"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery ("select name, number from pcmtable where number < 2"); while(rs.next()) System.out.println(rs.getString(1) + " (" + rs.getInt(2) + ")"); stmt.close() con.close(); } catch(Exception e){ System.err.println(e); }}}

JDBC Program-1:Display
import java.sql.*; import javax.swing.*; import java.awt.*; class frame1 extends JFrame { JLabel j1,j2,j3; Connection conn; Statement stmt; ResultSet rs;

table data

frame1 () { Container con=getContentPane(); con.setLayout(new FlowLayout()); j1=new JLabel(); j2=new JLabel(); j3=new JLabel(); con.add(j1); con.add(j2); con.add(j3);

try

{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); conn = DriverManager.getConnection("jdbc:odbc:mydsn1"); stmt=conn.createStatement(); rs=stmt.executeQuery("Select * from customer1");

while(rs.next()) { j1.setText(j1.getText()+ "" +rs.getString(1)); j2.setText(j2.getText()+ "" +rs.getString(2)); j3.setText(j3.getText()+""+rs.getInt(3)); } rs.close(); stmt.close(); conn.close(); }

catch(ClassNotFoundException ce) { j1.setText(ce.getMessage()); } catch(SQLException se) { j1.setText(se.getMessage()); } } }

public class demo { public static void main(String a[]) { frame1 f=new frame1(); f.setVisible(true); } }

Program-2: add, update & display


import import import import java.sql.*; javax.swing.*; java.awt.*; java.awt.event.*;

class frame1 extends JFrame implements ActionListener { JLabel j1,j2,j4; JTextField t1,t2; JButton b1,b2,b3; Connection conn; Statement stmt; ResultSet rs;

frame1() { Container con=getContentPane(); con.setLayout(new FlowLayout()); setSize(300,300); t1=new JTextField(10); con.add(t1); t2=new JTextField(10); con.add(t2); b1=new JButton("add"); b1.addActionListener(this); con.add(b1); b2=new JButton("update"); b2.addActionListener(this); con.add(b2);

b3=new JButton("display"); b3.addActionListener(this); con.add(b3); j1=new JLabel(); con.add(j1); j2=new JLabel(); con.add(j2); j4=new JLabel(); con.add(j4);

try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); conn = DriverManager.getConnection("jdbc:odbc:dsn2"); stmt=conn.createStatement(); }

catch(ClassNotFoundException ce) { j1.setText(ce.getMessage()); } catch(SQLException se) { j1.setText(se.getMessage()); } }

public void actionPerformed(ActionEvent ae) { if(ae.getActionCommand().equals("add")) { try { String sname=t1.getText(); int p=Integer.parseInt(t2.getText()); String s="insert into result(name,per) values('"+sname+"',"+p+")"; stmt.executeUpdate(s); conn.commit(); j1.setText("row is added"); }

catch(SQLException se) { j1.setText(se.getMessage()); } catch(Exception e) { j1.setText(e.getMessage()); } }

if(ae.getActionCommand().equals("update")) { try { String sname=t1.getText(); int p=Integer.parseInt(t2.getText()); String s="update result set per="+p+" where name='"+sname+"'"; int i=stmt.executeUpdate(s); conn.commit(); j1.setText("row is updated"+i); }

catch(SQLException se) { j1.setText(se.getMessage()); } catch(Exception e) { j1.setText(e.getMessage()); } }

if(ae.getActionCommand().equals("display")) { try { String s="Select * from result"; ResultSet rs1=stmt.executeQuery(s); while(rs1.next()) { j2.setText(j2.getText()+","+rs1.getString(1)); j4.setText(j4.getText()+","+rs1.getString(2)); } }

catch(SQLException se) { j1.setText(se.getMessage()); } catch(Exception e) { j1.setText(e.getMessage()); } } } }

public class demo3 { public static void main(String a[]) { frame1 f=new frame1(); f.setVisible(true); } }

Program-3: To demonstrate executebatch()


import import import import java.awt.*; java.awt.event.*; javax.swing.*; java.sql.*;

class frame2 extends JFrame implements ActionListener { Connection conn; Statement stmt; JLabel j1; JButton b1;

frame2() { Container con=getContentPane(); con.setLayout(new FlowLayout()); setSize(300,300); b1=new JButton("Click"); b1.addActionListener(this); con.add(b1); j1=new JLabel(); con.add(j1);

try

} catch(ClassNotFoundException ce) { j1.setText(ce.getMessage()); } catch(SQLException se) { j1.setText(se.getMessage()); }

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); conn=DriverManager.getConnection("jdbc:odbc:dsn2"); stmt=conn.createStatement();

public void actionPerformed(ActionEvent ae) { try { stmt.clearBatch(); String s1="insert into result values('sophia',60)"; stmt.addBatch(s1); String s2="update result set per=20 where name='seema'"; stmt.addBatch(s2); stmt.executeBatch(); }

catch(SQLException se) { j1.setText(se.getMessage()); } } }

public class demo4 { public static void main(String a[]) { frame2 f=new frame2(); f.setVisible(true); } }

About Prepared Statements


Prepared Statements are used for queries that are executed many times They are parsed (compiled) by the DBMS only once Column values can be set after compilation Instead of values, use ? Hence, Prepared Statements can be though of as statements that contain placeholders to be substituted later with actual values

Querying with PreparedStatement


String queryStr = "SELECT * FROM Items " + "WHERE Name = ? and Cost < ?"; PreparedStatement pstmt = con.prepareStatement(queryStr); pstmt.setString(1, "t-shirt"); pstmt.setInt(2, 1000); ResultSet rs = pstmt.executeQuery();

Updating with PreparedStatement


String deleteStr = DELETE FROM Items " + "WHERE Name = ? and Cost > ?";

PreparedStatement pstmt = con.prepareStatement(deleteStr);


pstmt.setString(1, "t-shirt"); pstmt.setInt(2, 1000); int delnum = pstmt.executeUpdate();

Demonstrate use of prepared statement


import import import import java.awt.*; javax.swing.*; java.awt.event.*; java.sql.*;

class frame3 extends JFrame implements ActionListener { JTextField t1,t2; JButton b1; Connection conn; PreparedStatement pstmt; ResultSet rs;

frame3() { setVisible(true); setSize(300,300); Container con=getContentPane(); con.setLayout(new FlowLayout()); t1=new JTextField(10); con.add(t1); t2=new JTextField(10); con.add(t2); b1=new JButton("add"); b1.addActionListener(this); con.add(b1);

public void actionPerformed(ActionEvent ae) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); conn=DriverManager.getConnection("jdbc:odbc:dsn2"); String sql="insert into result values(?,?)"; String sname=t1.getText(); int iper=Integer.parseInt(t2.getText()); PreparedStatement pstmt=conn.prepareStatement(sql); pstmt.setString(1,sname); pstmt.setInt(2,iper); pstmt.executeUpdate(); conn.commit(); pstmt.close(); conn.close(); }

catch(SQLException se) { System.out.println(se.getMessage()); } catch(ClassNotFoundException ce) { System.out.println(ce.getMessage()); }

}
}

public class demo5 { public static void main(String s[]) { frame3 f1=new frame3(); f1.setVisible(true);

}
}

ResultSet Types
ResultSet types The ResultSet type specifies the following about the ResultSet: Whether the ResultSet is scrollable. The types of Java(TM) Database Connectivity (JDBC) ResultSets that are defined by constants on the ResultSet interface.

Definitions of these ResultSet types are as follows: TYPE_FORWARD_ONLY


A cursor that can only be used to process from the beginning of a ResultSet to the end of it. This is the default type.

TYPE_SCROLL_INSENSITIVE

A cursor that can be used to scroll in various ways through a ResultSet. This type of cursor is insensitive to changes made to the database while it is open. It contains rows that satisfy the query when the query was processed or when data is fetched.

TYPE_SCROLL_SENSITIVE
A cursor that can be used to scroll in various ways through a ResultSet. This type of cursor is sensitive to changes made to the database while it is open. Changes to the database have a direct impact on the ResultSet data.

When creating a Statement object, you need to specify two arguments to the method createStatement().The first argument indicates the type of a ResultSet object: ResultSet.TYPE_FORWARD_ONLY: cursor may move only forward ResultSet.TYPE_SCROLL_INSENSITIVE: scrollable but generally not sensitive to changes made by others ResultSet.TYPE_SCROLL_SENSITIVE: scrollable and generally sensitive to changes made by others The second argument: ResultSet.CONCUR_READ_ONLY: the concurrency mode that may not be updated ResultSet.CONCUR_UPDATABLE: the concurrency mode that may be updated

Program to display first,previous,next and last record.


import import import import java.awt.*; javax.swing.*; java.sql.*; java.awt.event.*;

class frame5 extends JFrame implements ActionListener { JLabel j1; JButton b1,b2,b3,b4; Connection conn; Statement stmt; ResultSet rs;

frame5() { Container con=getContentPane(); con.setLayout(new FlowLayout()); setSize(300,300); b1=new JButton("first"); b1.addActionListener(this); con.add(b1); b2=new JButton("previous"); b2.addActionListener(this); con.add(b2); b3=new JButton("next"); b3.addActionListener(this); con.add(b3); b4=new JButton("last"); b4.addActionListener(this); con.add(b4); j1=new JLabel(); con.add(j1);

try

{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); conn = DriverManager.getConnection("jdbc:odbc:dsn2"); stmt=conn.createStatement(ResultSet.TYPE_SCROLL _SENSITIVE, ResultSet.CONCUR_UPDATABLE); rs=stmt.executeQuery("Select * from result"); }

catch(ClassNotFoundException ce) { j1.setText(ce.getMessage()); } catch(SQLException se) { j1.setText(se.getMessage()); } }

public void actionPerformed(ActionEvent ae) { if(ae.getActionCommand().equals("first")) { try { rs.first();

j1.setText(rs.getString("name"));
} catch(SQLException se) { j1.setText(se.getMessage()); }

if(ae.getActionCommand().equals("next")) { try { rs.next(); if(rs.isAfterLast()) rs.last(); j1.setText(rs.getString("name")); } catch(SQLException se) { j1.setText(se.getMessage()); }

if(ae.getActionCommand().equals("last")) { try { rs.last(); j1.setText(rs.getString("name")); } catch(SQLException se) { j1.setText(se.getMessage()); }

if(ae.getActionCommand().equals("previous")) { try { rs.previous(); if(rs.isBeforeFirst()) rs.first(); j1.setText(rs.getString("name")); } catch(SQLException se) { j1.setText(se.getMessage()); }

} } }

public class demo6 { public static void main(String a[]) { frame5 f=new frame5(); f.setVisible(true); } }

Output of demo6:

Vous aimerez peut-être aussi