Unit 5 Jdbc2

86
JDBC

Transcript of Unit 5 Jdbc2

Page 1: Unit 5 Jdbc2

JDBC

Page 2: Unit 5 Jdbc2

• JDBC is Java API twhich allows the Java programmers to access database management system from Java code.

• It is a java API which enables the java programs to execute SQL statements.

• Defines how a java programmer can access the   database in tabular format from Java code using a set of  standard interfaces and classes written in the Java programming language.

• JDBC provides methods for querying and  updating the data in Relational Database Management system  such as SQL, Oracle etc

Page 3: Unit 5 Jdbc2

JDBC Driver Types

                  • Type 1 JDBC-to-ODBC Driver.

• Type 2 Java/Native Code Driver.

• Type 3 JDBC Driver.

• Type 4 JDBC Driver.

Page 4: Unit 5 Jdbc2

Type 1 JDBC-to-ODBC Driver

The JDBC type 1 driver, also known as the JDBC-ODBC bridge is a database driver implementation that employs the ODBC driver to connect to the database.

The driver converts JDBC method calls into ODBC function calls.

The driver is implemented in the sun.jdbc.odbc.JdbcOdbcDriver class and comes with the Java 2 SDK, Standard Edition.

The driver is platform-dependent as it makes use of ODBC which in turn depends on native libraries of the operating system. Also, using this driver has got other dependencies such as ODBC must be installed on the computer having the driver and the database which is being connected to must support an ODBC driver.

Type 1 is the simplest of all but platform specific i.e only to Microsoft platform.

Type 1 drivers are "bridge" drivers. They use another technology such as Open Database Connectivity (ODBC) to communicate  with a database. This is an advantage because ODBC drivers exist for many Relational Database Management System (RDBMS) platforms.

A Type 1 driver needs to have the bridge driver installed and configured before JDBC can be used with it. This can be a serious drawback for a production application.

Page 5: Unit 5 Jdbc2

Functions:

•  Translates query obtained by JDBC into corresponding ODBC query, which is then handled by the ODBC driver. 

•  Sun provides a JDBC-ODBC Bridge driver. sun.jdbc.odbc.JdbcOdbcDriver.

• Client -> JDBC Driver -> ODBC Driver -> Database

• There is some overhead associated with the translation work to go from JDBC to ODBC.

Advantages:Almost any database for which ODBC driver is installed, can be accessed.

Disadvantages:

• Performance overhead since the calls have to go through the JDBC overhead bridge to the ODBC driver, then to the native database connectivity interface.

• The ODBC driver needs to be installed on the client machine.

Page 6: Unit 5 Jdbc2

Type 1 JDBC Driver

Page 7: Unit 5 Jdbc2

Type 2 Java/Native Code Driver

• The JDBC type 2 driver, also known as the Native-API driver is a database driver implementation that uses the client-side libraries of the database.

• The driver converts JDBC method calls into native calls of the database API.

• A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS.

• Type 2 drivers use a native API to communicate with a database system.

Page 8: Unit 5 Jdbc2

Functions:

• This type of driver converts JDBC calls into calls to the client API for that database.

• Client -> JDBC Driver -> Vendor Client DB Library -> Database

Advantage

Better performance than Type 1 since no jdbc to odbc translation is needed.

Disadvantages

• The vendor client library needs to be installed on the client machine.

• Not all databases give the client side library.

Page 9: Unit 5 Jdbc2

Type 2 JDBC Driver

Page 10: Unit 5 Jdbc2

• The JDBC type 3 driver, also known as the network-protocol driver is a database driver implementation which makes use of a middle-tier between the calling program and the database.

• The middle-tier (application server) converts JDBC calls directly or indirectly into the vendor-specific database protocol.

• The same driver can be used for multiple databases. It depends on the number of databases the middleware has been configured to support.

• Making use of the middleware provides additional advantages of security and firewall access.

• A net-protocol fully Java technology-enabled driver translates JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS protocol by a server.

Type 3 JDBC Driver

Page 11: Unit 5 Jdbc2

Functions:

• Follows a three tier communication approach.

• Can interface to multiple databases - Not vendor specific.

• The JDBC Client driver written in java, communicates with a middleware-net-server using a database independent  protocol, and then this net server translates this request into database commands for that database.

• Thus the client driver to middleware communication is database independent.

• Client -> JDBC Driver -> Middleware-Net Server -> Any Database

• Advantages

• Since the communication between client and the middleware server is database independent, there is no need for the vendor db library on the client machine. Also the client to middleware need'nt be changed for a new database.

eg. Weblogic.

• At client side a single driver can handle any database.(It works provided the middlware supports that database)

Disadvantages

• Requires database-specific coding to be done in the middle tier.

•  An extra layer added may result in a time-bottleneck. But typically this is overcome by providing efficient middleware

Page 12: Unit 5 Jdbc2

Type 3 JDBC Driver

Page 13: Unit 5 Jdbc2

Type 4 JDBC Driver

• The JDBC type 4 driver, also known as the native-protocol driver is a database driver implementation that converts JDBC calls directly into the vendor-specific database protocol.

• The type 4 driver is written completely in Java and is hence platform independent.

• Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver.

Page 14: Unit 5 Jdbc2

Functions

• Type 4 drivers are entirely written in Java that communicate directly with a vendor's database. No translation or middleware layers, are required, improving performance.

• The driver converts JDBC calls into the vendor-specific database protocol so that client applications can communicate directly with the database server.

• Completely implemented in Java to achieve platform independence.

• e.g include the widely used Oracle thin driver - oracle.jdbc.driver. OracleDriver which connect to jdbc:oracle:thin URL format.

• Client Machine -> Native protocol JDBC Driver -> Database server

Advantages

These drivers don't translate the requests into db request to ODBC or pass it to client api for the db, nor do they need a middleware layer for request indirection. Thus the performance is considerably improved.

DisadvantageAt client side, a separate driver is needed for each database.

Page 15: Unit 5 Jdbc2

Type 4 JDBC Driver

Page 16: Unit 5 Jdbc2

JDBC

Type I“Bridge”

Type II“Native”

Type III“Middleware”

Type IV“Pure”

ODBCODBCDriver

.lib

MiddlewareServer

JDBC Drivers

Page 17: Unit 5 Jdbc2

Brief Overview of the JDBC Process

Loading the JDBC driver

Connecting to the DBMS

Creating and executing a statement.

Processing data returned by the DBMS

Terminating the connection with the DBMS

Page 18: Unit 5 Jdbc2

Loading the JDBC driver

The JDBC driver must be loaded before connect to the DBMS.

The driver is loaded by calling the Class.forName() method and passing it the name of

the driver.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Page 19: Unit 5 Jdbc2

Connecting to the DBMS

Once the driver is loaded, connect to the DBMS using method

DriverManager.getConnection()

The DriverManager.getConnection() method is passed the URL of the database, and the userID and password if

required by the DBMS.

The URL is a String object that contains the driver name and the name of the database that is being accessed.

The DriverManager.getConnection() method returns a Connection interface that is used throughout the process

to reference the database.

Page 20: Unit 5 Jdbc2

String url =“jdbc:odbc:CustomerInformation”;

String userID=“sjec”;

String password = “comp”

try

{

Class.forName(“sun.jdbc.odbc.JdbcOdbcDrive”);

Connection conn = DriverManager.getConnection(url,userID,password);

}

Page 21: Unit 5 Jdbc2

Creating and executing a statement.

The con.createStatement() method is used to create a statement object.

The statement object is then used to execute a query and return a resultset object that contains the response from the

DBMS.

Statement stmt;

ResultSet rs;

Try

{

String query = “SELECT * FROM customers”;

stmt = con.createStatement();

rs = stmt.executeQuery(query);

con.close();

}

Page 22: Unit 5 Jdbc2

Processing data returned by the DBMSThe java.sql.ResultSet object is assigned the results received from the DBMS after the

query is processed.

The java.sql.ResultSet object consists of methods used to interact with data.

ResultSet rs;

String FirstName;

String LastName;

while(rs.next());

{

FirstName = rs.getString(FirstName);

LastName = rs.getString(LastName);

System.out.println(FirstName+” “+LastName);

}

Page 23: Unit 5 Jdbc2

Terminating the connection with the DBMSThe connection to the DBMS is terminated by using close() method of the Connection object once finished

accessing the DBMS.

con.close();

Page 24: Unit 5 Jdbc2

JDBC ArchitectureJava ApplicationJava Application

JDBC Driver ManagerJDBC Driver Manager

(T2) Java Portion

(T2) Java Portion

(T1) JDBC-ODBC Bridge(T1) JDBC-

ODBC Bridge(T4) JavaDriver tovendor'sprotocol

(T4) JavaDriver tovendor'sprotocolODBC DriverODBC Driver

Proprietary, vendor-specificdatabase access protocol

Provided withSun's JDK

JDBC DriversNative PortionNative Portion

(T3) Java Client

(T3) Java Client

ServerComponent

ServerComponent

Page 25: Unit 5 Jdbc2

Database Connection

Before the connection is made, the JDBC driver must be loaded and registered with the DriverManager.

The purpose of loading and registering the JDBC driver is to bring the JDBC driver into the JVM. The JDBC driver

is automatically registered with the DriverManager once the JDBC driver is loaded and is therefore available to the

JVM and can be used.

The Class.forName() methods throws a ClassNotFoundException.

try

{

Class.forName(“sun.jdbc.odbc.JdbcOdbcDrive”);

}

catch(ClassNotFoundException error)

{

System.out.println(“Unable to load JDBC/ODBC bridge”+error.getMessage());

}

Page 26: Unit 5 Jdbc2

The Connection

• After the JDBC driver is successfully loaded and registered, connect to the database.

• A Connection object represents a connection with a database. When we connect to a database by using connection method, we create a Connection Object, which represents the connection to the database.

• The datasource that the JDBC component will connect to is defined using the URL format. The URL consist of 3 parts. These are

jdbc which indicates that the JDBC protocol is to be used to read the URL.

<subprotocol> which is the JDBc driver name.

<subname> which is the name of the database.

ex:String url = “jdbc:odbc:sjec”;

Page 27: Unit 5 Jdbc2

The connection to the databse is established by using one of the 3 getConnection method.

getConnection(String url)

getConnection(String url,String id,String password);

getConnection(String url, Properties prop);

Ex: getConnection(“jdbc:odbc:sjec”, ”cse”, ”sem7”);

Page 28: Unit 5 Jdbc2

• The getConnection() method request access to the database from the DBMS. It is up to the DBMS to grant or reject access.

• A connection object is returned by the getConnection() method if access is granted.

otherwise getConnection() method throws a SQLException.

• Sometimes the DBMS grants access to a database to anyone.

• In this case getConnection(String url) method is used.

Page 29: Unit 5 Jdbc2

String url = “jdbc:odbc:sjec”;

try

{

Class.forName(“sun.jdbc.odbc.JdbcOdbcDrive”);

conn = DriverManager.getConnection(url)

}

catch(ClassNotFoundException error)

{

System.out.println(“Unable to load JDBC/ODBC bridge”+error.getMessage());

}

catch(SQLException error)

{

System.out.println(“can not connect to the datanase”+error.getMessage());

}

Page 30: Unit 5 Jdbc2

Some databases limit access to authorized users and require to supply a userID

and password .

Page 31: Unit 5 Jdbc2

String url =“jdbc:odbc:CustomerInformation”;

String userID=“sjec”;

String password = “comp”

Private Connection conn;

try

{

Class.forName(“sun.jdbc.odbc.JdbcOdbcDrive”);

conn = DriverManager.getConnection(url,userID,password);

}

catch(ClassNotFoundException error)

{

System.out.println(“Unable to load JDBC/ODBC bridge”+error.getMessage());

}

catch(SQLException error

{

System.out.println(“can not connect to the datanase”+error.getMessage());

}

Page 32: Unit 5 Jdbc2

Some DBMS requires additional information.

This additional information is referred to as properties and must be associated with a

Properties object, which is passed to the DBMS as a getConnection() parameter.

Page 33: Unit 5 Jdbc2

Connection con ;

Properties props = new Properties();

try

{

FileInputStream fis = new FileInputStream(“DBProps.txt”);

props.load(fis);

}

catch(IOException err)

{

System.out.println(“error loading property file”);

}

try

{

Class.forName(“sun.jdbc.odbc.JdbcOdbcDrive”);

conn = DriverManager.getConnection(url,props);

}

catch(ClassNotFoundException error)

{

System.out.println(“Unable to load JDBC/ODBC bridge”+error.getMessage());

}

catch(SQLException error)

{

System.out.println(“can not connect to the datanase”+error.getMessage());

}

Page 34: Unit 5 Jdbc2

Associating the JDBC/ODBC bridge with the Database

1 select start | settings | control panel

2 select ODBC 32 to display the ODBC DataSourceAdministrator

3 Add new user by selecting the add button

4 select the driver and then finish

5 Enter the name of the datasourcename

6 .

.

..

..

Page 35: Unit 5 Jdbc2

Associating the JDBC/ODBC bridge with the Database

1. Make sure you have the Access 95 ODBC drivers installed. These ODBC drivers can be installed from theAccess install program.

2. Select Start Menu|Settings|Control Panels.

3. Click on 32 bit ODBC.

4. Click on the Add button and choose the Access Driver.

5. Type in a Data Source Name and Description (anything you like).

6. In the Database area, click on Select.

7. Select the Access database file; a sample database is located in MSoffice\ACCESS\Samples (if you installed it during the Access installation). However, you can specify any Access database you want.

8. You may want to click on the Advanced button and set the Username and Password. Click on OK and then on Close to complete the configuration

Page 36: Unit 5 Jdbc2

Statement Objects

Once a connection to the database is opened, then create and sends a

query to access data contained in the database. The query is written SQL.

One of the 3 types of Statement objects is used to execute the query.

1 Statement which executes a query immediately.

2 PrepapedStatement which is used to execute a compiled query

3 CallableStatement, which is used to execute store procedures.

Page 37: Unit 5 Jdbc2

The Statement Object

3 methods

executeQuery();

executeUpdate(); method is used to execute queries that contain UPDATE and DELETE SQL statement.

execute(); method is used when there may be multiple results returned.

Page 38: Unit 5 Jdbc2

String url =“jdbc:odbc:CustomerInformation”;

String userID=“sjec”;

String password = “comp”

Private Connection conn;

try

{

Class.forName(“sun.jdbc.odbc.JdbcOdbcDrive”);

conn = DriverManager.getConnection(url,userID,password);

}

catch(ClassNotFoundException error)

{

System.out.println(“Unable to load JDBC/ODBC bridge”+error.getMessage());

}

catch(SQLException error)

{

System.out.println(“can not connect to the datanase”+error.getMessage());

}

Page 39: Unit 5 Jdbc2

Statement stmt;

try

{

String query = “SELECT * FROM customers”;

stmt = con.createStatement();

rs = stmt.executeQuery(query);

con.close();

}

catch(SQLException error)

{

System.out.priintln( “cannot connect to the database”);

}

Page 40: Unit 5 Jdbc2

executeUpdate()

Page 41: Unit 5 Jdbc2

String url =“jdbc:odbc:CustomerInformation”;

String userID=“sjec”;

String password = “comp”

Private Connection conn;

try

{

Class.forName(“sun.jdbc.odbc.JdbcOdbcDrive”);

conn = DriverManager.getConnection(url,userID,password);

}

catch(ClassNotFoundException error)

{

System.out.println(“Unable to load JDBC/ODBC bridge”+error.getMessage());

}

catch(SQLException error)

{

System.out.println(“can not connect to the datanase”+error.getMessage());

}

Page 42: Unit 5 Jdbc2

try

{

String query = “UPDATE customers set PAID =‘T’ where balance = ‘0”;

stmt = con.createStatement();

rs = stmt.executeUpdate(query);

con.close();

}

catch(SQLException error)

{

System.out.priintln( “cannot connect to the database”);

}

Page 43: Unit 5 Jdbc2

PreparedStatement Object

Page 44: Unit 5 Jdbc2

String url =“jdbc:odbc:CustomerInformation”;

String userID=“sjec”;

String password = “comp”

Private Connection conn;

try

{

Class.forName(“sun.jdbc.odbc.JdbcOdbcDrive”);

conn = DriverManager.getConnection(url,userID,password);

}

catch(ClassNotFoundException error)

{

System.out.println(“Unable to load JDBC/ODBC bridge”+error.getMessage());

}

catch(SQLException error)

{

System.out.println(“can not connect to the datanase”+error.getMessage());

}

Page 45: Unit 5 Jdbc2

try

{

String query = “SELECT * FROM customers WHERE CustNum = ?”;

PreparedStatemnt ps = con.preparedStatement();

ps.setString(1,”123”);

rs = ps.executeQuery(query);

ps.close();

}

catch(SQLException error)

{

System.out.priintln( “cannot connect to the database”);

}

Page 46: Unit 5 Jdbc2

CallableStatement

• The CallableStatement object is used to used to call a stored procedure.

• The CallableStatement object uses 3 types of parameters when calling a stored procedure.

These parameters are IN, OUT and INOUT.

• The IN parameter contain any data that needs to be passed to the stored procedure and whose value is assigned using the setxxx() method.

• The OUT parameter contain the value returned by the stored procedure. The OUT parameter must be registered using the registerOutParameter() and is retrieved by getxxx() method.

• The INOUT parameter is a single parameter is a single parameter is used to both pass information to the stored procedure and retrieve information from a stored procedure.

• The registerOutParameter requires 2 parameter. The first parameter is the integer that represents the number of the parameter. The second parameter is the data type of the value returned by the stored procedure.

Page 47: Unit 5 Jdbc2

String url =“jdbc:odbc:CustomerInformation”;

String userID=“sjec”;

String password = “comp”

Private Connection conn;

try

{

Class.forName(“sun.jdbc.odbc.JdbcOdbcDrive”);

conn = DriverManager.getConnection(url,userID,password);

}

catch(ClassNotFoundException error)

{

System.out.println(“Unable to load JDBC/ODBC bridge”+error.getMessage());

}

catch(SQLException error)

{

System.out.println(“can not connect to the datanase”+error.getMessage());

}

Page 48: Unit 5 Jdbc2

try

{

String query = “ { CALL LastOrderNumber(?) } “;

CallableStatement cs = con.prepareCall(query);

cs.registerOutParameter(1, Types.VARCHAR);

csstatement.execute();

lastOrdrNumber = cs.getString();

cs.close()

}

catch(SQLException error)

{

System.out.println(“SQL error”+error);

}

con.close();

Page 49: Unit 5 Jdbc2

ResultSet

The ResultSet object contains methods that are used to copy data from the Result into a Java

variable for further processing.

Data in a ResultSet object is logically organized into a virtual table consisting of rows and column.

Resultset object also contains metadata such as column names, column size, and column data

types.

The ResultSet uses a virtual curser to point to a row of the virtual table.

We must move the virtual curser to each row and use other methods of the ResultSet object to

interact with the data stored in columns of that row.

The virtual curser is positioned above the first row of the data when the ResultSet is returned by

the executeQuery() method. This means that virtual curser must be moved to the first row using

next() method.

Page 50: Unit 5 Jdbc2

• The next() method returns a boolean true if the row contains a data. Otherwise, a boolean false is returned indicating that no more rows exist in the ResultSet.

• Once the virtual curser points to a row, the getxxx() method is used to copy data from the row to a collection , object or variable.

• The getxxx() parameter requires one parameter, which is an integer that represent he number of column that contains the data.

Ex: getInt(1);

getString(2);

getInt(3);

Page 51: Unit 5 Jdbc2

String url =“jdbc:odbc:CustomerInformation”;

String userID=“sjec”;

String password = “comp”

Private Connection conn;

try

{

Class.forName(“sun.jdbc.odbc.JdbcOdbcDrive”);

conn = DriverManager.getConnection(url,userID,password);

}

catch(ClassNotFoundException error)

{

System.out.println(“Unable to load JDBC/ODBC bridge”+error.getMessage());

}

catch(SQLException error)

{

System.out.println(“can not connect to the datanase”+error.getMessage());

}

Page 52: Unit 5 Jdbc2

try

{ String query = “SELECT FirstName, LastName FROM Customers”;

stmt = con.createStatement();

rs = stmt.executeUpdate(query);

con.close();

}

catch(SQLException error)

{

System.out.priintln( “cannot connect to the database”);

}

try

{ while(rs.next())

{

FirstName = rs.getString(1);

LastName = rs.getString(2);

System.out.println(FirstName+” “+LastName);

}

}

Catch(SQLException error)

{ System.out.println(“data entry error”);

}

Page 53: Unit 5 Jdbc2

Scrollable ResultSetThere are 6 methods of the ResultSet object that are used to position the virtual cluster.

next()

previous()

first()

last()

absolute()

relative()

getRow()

The absolute method positions the virtual curster at the row specified by the integer

passed as a parameter to the absolute() method.

The relative() method moves the virtual curser the specified number of rows contained

in the parameter. The parameter is a positive or negative integer where the sign

represents the direction the virtual curser is moved.

getRow() method returns an integer that represents the number of current rows in the

ResultSet.

Page 54: Unit 5 Jdbc2

The Statement object that is created using the createStatement() of the Connection

object must be setup to handle a scrollable ResultSet by passing the createStatement()

method one of three constant.

TYPE_FORWARD_ONLY

TYPE_SCROLL_INSENSITIVE

TYPE_SCROLL_SENSITIVE.

TYPE_FOREWARD_ONLY is the default setting.

The TYPE_SCROLL_INSENSITIVE constant makes the Resultset insensitive to the changes

made by another component.

Page 55: Unit 5 Jdbc2

String url =“jdbc:odbc:CustomerInformation”;

String userID=“sjec”;

String password = “comp”

Private Connection conn;

try

{

Class.forName(“sun.jdbc.odbc.JdbcOdbcDrive”);

conn = DriverManager.getConnection(url,userID,password);

}

catch(ClassNotFoundException error)

{

System.out.println(“Unable to load JDBC/ODBC bridge”+error.getMessage());

}

catch(SQLException error)

{

System.out.println(“can not connect to the datanase”+error.getMessage());

}

Page 56: Unit 5 Jdbc2

try { String query = “SELECT FirstName, LastName FROM Customers”;

stmt = con.createStatement(TYPE_SCROLL_INSENSITIVE);

rs = stmt.executeUpdate(query);

con.close();

}

catch(SQLException error) {

System.out.priintln( “cannot connect to the database”); }

try

{ while(rs.next())

{

rs.last();

rs.first();

FirstName = rs.getString(1);

LastName = rs.getString(2);

System.out.println(FirstName+” “+LastName);

}

}

catch(SQLException error)

{ System.out.println(“data entry error”);

}

Page 57: Unit 5 Jdbc2

Updatable ResultSet

Rows contained in the ResultSet can be updatable by passing the createStatemenet() method of the

method of the Connection object the CONQUER_UPDATABLE.

Alternatively , the CONQUER_READ_ONLY constant can be passed to the createStatement method

to prevent the ResultSet from being updated.

There are 3 ways in which a ResultSet can be channged.

1 updating values in a row

2 deleting a row

3 inserting a new row.

Page 58: Unit 5 Jdbc2

Update ResultSet

• Once a executeQuery method of the Statement object returns a ResultSet, the updatexxx() method is used to change the value of a column in the current row of the resultset.

• The updatexxx method required 2 parameters.

• The update Row() method is called after all the updatexxx() methods are called.

• The changes only occur in the ResultSet. The corresponding row in the table remains unchanged.

Page 59: Unit 5 Jdbc2

Update ResultSetString url = "jdbc:odbc:CustomerInformation";

String userID = "jim";

String password = "keogh";

Statement st;

ResultSet rs;

Connection con;

try

{

Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver");

con = DriverManager.getConnection(url,userID,password);

}

catch (ClassNotFoundException error)

{

System.err.println("Unable to load the JDBC/ODBC bridge." + error);

System.exit(1);

}

catch (SQLException error)

{

System.err.println("Cannot connect to the database." + error);

System.exit(2);

}

Page 60: Unit 5 Jdbc2

try {

String query = "SELECT FirstName,LastName FROM Customers WHERE FirstName = 'Mary' and LastName = 'Smith'";

st = con.createStatement(ResultSet.CONCUR_UPDATABLE);

rs = st.executeQuery (query);

}

catch ( SQLException error )

{

System.err.println("SQL error." + error);

System.exit(3);

}

boolean Records = Results.next();

try {

Results.updateString ("LastName", "Smith");

Results.updateRow();

st.close();

}

catch (SQLException error ) {

System.err.println("Data display error." + error);

System.exit(5);

}

Page 61: Unit 5 Jdbc2

Delete Row in the ResultSet.

• rs.deleteRow(10)

• Or

• rs.absolute(10);

• rs.deleteRow()

Page 62: Unit 5 Jdbc2

Insert Row in the ResultSet

• Similar to update the Resultset.

• The insertRow method is called after the updatexxx() method.

Page 63: Unit 5 Jdbc2

String url = "jdbc:odbc:CustomerInformation";

String userID = "jim";

String password = "keogh";

Statement st

ResultSet rs;

Connection con;

try {

Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver");

con = DriverManager.getConnection(url,userID,password);

}

catch (ClassNotFoundException error) {

System.out.println("Unable to load the JDBC/ODBC bridge." + error);

System.exit(1);

}

catch (SQLException error) {

System.out.println("Cannot connect to the database." + error);

System.exit(2);

}

Page 64: Unit 5 Jdbc2

try {

String query = "SELECT FirstName,LastName FROM Customers";

st = con.createStatement(CONCUR_UPDATABLE);

rs = DataRequest.executeQuery (query);

}

catch ( SQLException error )

{

System.out.println("SQL error." + error);

System.exit(3);

}

boolean Records = rs.next();

try {

rs.updateString (1, "Tom");

rs.updateString (2, "Smith");

rs.insertRow();

rs.close();

}

catch (SQLException error ) {

System.out.println("Data display error." + error);

System.exit(5);

}

Page 65: Unit 5 Jdbc2

Transaction Processing

A database transaction consist of a set of SQL statements, each of which must be successfully completed for the

transaction to be completed.

If one fails, SQL statements that executed successfully up to that point in the transaction must be rolled back.

A database transaction is not completed until the commit() method of the Connection object is called. All SQL

statements executed prior to the call to the commit() method can be rolled back. However once the commit()

method is called, none of the SQL statements can be rolled back.

The commit() method must be called regardless if the SQL statements is part of a transaction or not.

commit method is automatically called , because DBMS has an AutoCommit features that is by default set to

true.

Page 66: Unit 5 Jdbc2

While is processing a transaction, the AutoCommit features must be deactivated by calling

setAutoCommit(false);

Once the transaction is completed, the setAutoCommit(true) is called again to reactivate the

AutoCommit feature.

Page 67: Unit 5 Jdbc2

String url = "jdbc:odbc:CustomerInformation";

String userID = "jim";

String password = "keogh";

Statement st1,st2 ;

Connection con;

try {

Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver");

con = DriverManager.getConnection(url,userID,password);

}

catch (ClassNotFoundException error) {

System.out.println("Unable to load the JDBC/ODBC bridge." + error);

System.exit(1);

}

catch (SQLException error) {

System.out.println("Cannot connect to the database." + error);

System.exit(2);

}

Page 68: Unit 5 Jdbc2

try {

con.setAutoCommit(false)

String query1 = "UPDATE Customers SET Street = '5 Main Street' " +

"WHERE FirstName = 'Bob'";

String query2 = "UPDATE Customers SET Street = '10 Main Street' " +

"WHERE FirstName = 'Tim'";

st1= con.createStatement();

st2= con.createStatement();

st1.executeUpdate (query1 );

st2.executeUpdate (query2 );

con.commit();

st1.close();

st2.close();

con.close();

}

Page 69: Unit 5 Jdbc2

catch(SQLException ex) {

System.out.println("SQLException: " + ex.getMessage());

if (con != null) {

try {

System.out.println("Transaction is being rolled back ");

con.rollback();

}

catch(SQLException excep) {

System.out.print("SQLException: ");

System.out.println(excep.getMessage());

}

}

}

Page 70: Unit 5 Jdbc2

• A transactiobn may consist of many tasks, some of which don’t need to be rolled back should the entire transaction fail.

• Ex: Consider order processing. These include updating the customer account table inserting the order into the pending order table sending a customer a confirmation email.

• Technically, all 3 tasks must be completed before the transaction is considered completed. suppose the email server is down when the transaction is ready to send the customer a confirmation email. Should the entire transaction be rolled back ? Probably not since it is more important that the order continue to be processed(ie delivered). The confirmation notice can be sent once the email server is back online.

Page 71: Unit 5 Jdbc2

Savepoint :

We can control the number of tasks that are rolled back by using savepoint.

A savepoint is a virtual marker that defines the task at which the rollback stops

There can be many savepoints used in a transaction.

Each savepoint is identified by a unique name.

Savepoint s1 = con.setSavepoint ("sp1");

The savepoint name is then passed to the rollback() mathods to specify the point within the transaction

where the rollback is to stop.

The releaseSavepoint() method is called to remove the savepoint from the transaction.

The name of the savepoint that is to be removed is passed to the releaseSavepoint() method.

Page 72: Unit 5 Jdbc2

String url = "jdbc:odbc:CustomerInformation";

String userID = "jim";

String password = "keogh";

Statement st1, st2 ;

Connection con;

try {

Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver");

con = DriverManager.getConnection(url,userID,password);

}

catch (ClassNotFoundException error) {

System.out.println("Unable to load the JDBC/ODBC bridge." + error);

System.exit(1);

}

catch (SQLException error) {

System.out.println("Cannot connect to the database." + error);

System.exit(2);

}

Page 73: Unit 5 Jdbc2

try { con .setAutoCommit(false)

String query1 = "UPDATE Customers SET Street = '5 Main Street' " +

"WHERE FirstName = 'Bob'";

String query2 = "UPDATE Customers SET Street = '10 Main Street' " +

"WHERE FirstName = 'Tim'";

st1= con.createStatement();

st1.executeUpdate (query1);

Savepoint s1 = con.setSavepoint ("sp1");

st2= con.createStatement();

st2.executeUpdate (query2);

con.commit();

st1.close();

st2.close();

con.releaseSavepoint ("sp1");

con.close();

} catch ( SQLException error ){ try {

con.rollback(sp1); }

catch ( SQLException error ){

System.out.println("rollback error." + error.getMessage());

System.exit(3);

}

System.out.println("SQL error." + error. getMessage()););

System.exit(4);

}

Page 74: Unit 5 Jdbc2

addBatch method :

• Another way to combine SQL statement into a transaction is to batch together these statements into a single transaction and then execute the entire transaction.

• We can do this by using the addBatch() method of the Statement object.

• The addBatch() method receives a SQL statement as a parameter and places the SQL statement in the batch.

• Once all the SQL statements that comprise the transaction are included in the batch, the executeBatch() method is called to execute the enire batch at the same time.

• The executeBatch method() returns an int array that contains the number of SQL statements that were executed successfully.

• The batch can be cleared of SQL statements by using the clearBatch() method.

• The transaction must be committed using the commit() method.

Page 75: Unit 5 Jdbc2

String url = "jdbc:odbc:CustomerInformation";

String userID = "jim";

String password = "keogh";

Statement st;

Connection con;

try {

Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver");

con = DriverManager.getConnection(url,userID,password);

}

catch (ClassNotFoundException error) {

System.out.println("Unable to load the JDBC/ODBC bridge." + error);

System.exit(1);

}

catch (SQLException error) {

System.out.println("Cannot connect to the database." + error);

System.exit(2);

}

Page 76: Unit 5 Jdbc2

try {

con .setAutoCommit(false)

String query1 = "UPDATE Customers SET Street = '5 Main Street' " +

"WHERE FirstName = 'Bob'";

String query2 = "UPDATE Customers SET Street = '10 Main Street' " +

"WHERE FirstName = 'Tim'";

st= con.createStatement();

st.addBatch(query1);

st.addBatch(query2);

int [ ] updated = st.executeBatch ();

con.commit();

st1.close();

st2.close();

con.close();

}

catch(BatchUpdateException error) {

System.out.println("Batch error.");

System.out.println("SQL State: " + error.getSQLState());

System.out.println("Message: " + error.getMessage());

System.out.println("Vendor: " + error.getErrorCode());

Page 77: Unit 5 Jdbc2

int [ ] updated = error.getUpdatecount();

int count = updated.length();

for int - i = 0; i < count; i++) {

System.out.print (updated[i]);

}

SQLException sql = error;

While (sql != null)

{

System.out.println("SQL error " + sql);

sql = sql.getnextException();

}

try{

st.clearBatch();

}

catch(BatchUpdateException error) {

System.out.println("Unable to clear the batch: " + error.getMessage());

}

}

Page 78: Unit 5 Jdbc2

ResultSet Holdability

• Whenever the commit() method is called, all ResultSet objects that were created for the transaction are closed.

• We can control whether or not ResultSet objects are closed by passing following parameter to the createStatement()

HOLD_CURSORS_OVER_COMMIT

CLOSE_CURSORS_AT_COMMIT

Page 79: Unit 5 Jdbc2

RowSets

• The JDBC RowSets object is used to encapsulate a ResultSet for use with EJB.

• A RowSet object contains rows of data from the table that can be used in a disconnected operation.

Page 80: Unit 5 Jdbc2

Auto-Generated Keys• DBMS automatically generate unique keys for a table as rows are inserted into the table.

• The getGeneratedKeys() method of the Statement object is called to return keys genetated by the DBMS.

Page 81: Unit 5 Jdbc2

MetaData• Metadata is data about data.

• The DatabaseMetaData interface is used to retrieve information about databases, table, column, and indexes among other information about the DBMS.

• Metadata about the database is retrieved by calling getMetaData() of Connection object.

• The getMetaData() method returns a DatabaseMetaData object that contains information about the database and its component.

• DatabaseMetaData object contains following methods.

getDatabaseProductName()

getUserName()

getURL()

getSchemas()

getPrimaryKeys()

getProcedures()

getTables()

Page 82: Unit 5 Jdbc2

ResultSet Metadata

There are 2 types of metadata that can be retrieved from the DBMS.

• metadata that describes the database

• metadata that describes ResultSet

Metadata that describes the ResultSet is retrieved by calling the getMetaData() method of the ResultSet object.

This returns a Returns a ResultSetMetaData object.

ResultSetMetaData rm = rs.getMetaData();

ResultSetMetaData objects provides following methods.

getColumnCount()

getColumnName(int number);

getColumnType(int number);

Page 83: Unit 5 Jdbc2

Exceptions

There are 3 kinds of exceptions that are thrown by JDBC methods. These are

SQLException

SQLWarnings

DataTruncation.

SQLExceptions commonly reflect a SQL syntax error in a query. This exception is mostly

caused by connectivity issues with the database.

The SQLWarning throws warnings received by the Connection from the DBMS.

Whenever data is lost due to truncation of the data value, a DataTruncation exception is

thrown.

Page 84: Unit 5 Jdbc2

• execute() - will do the querying the database & also the update,insert,delete on the database.

• executeUpdate() - only the update,insert,delete on the database.

• executeQuery() - only the querying the database.

• --------------------------------------

• execute()- is for invoking the functions or stored procedures of SQL by the CallableStatement.

• executeUpdata()- is for the operations such as insert, update or delete on SQL by PreparedStatement, Statement.

• executeQuery() - is for operation select of Sql by PreparedStatement or Statement.

• ----------------------------------------

• executeUpdate() is for non selecting statements

• executeQuery() is for selecting statements.

• --------------------------------------------------------------------

Page 85: Unit 5 Jdbc2

• boolean execute() Executes the SQL statement in this PreparedStatement object, which may be any kind of SQL statement.

• ResultSet executeQuery() Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.

• int executeUpdate() Executes the SQL statement in this PreparedStatement object, which must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement.

Page 86: Unit 5 Jdbc2

• import java.util.*; String URL = "jdbc:oracle:thin:@amrood:1521:EMP"; Properties info = new Properties( ); info.put( "user", "username" ); info.put( "password", "password" ); Connection conn = DriverManager.getConnection(URL, info);